package cn.btks.resultintegration.achievements.service.impl;

import cn.btks.commonserver.pojo.PageList;
import cn.btks.commonserver.result.Constants;
import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.commonserver.util.*;
import cn.btks.commonserver.util.poi.PoitlUtil;
import cn.btks.resultintegration.achievements.dto.VerifyParamDto;
import cn.btks.resultintegration.achievements.pojo.*;
import cn.btks.resultintegration.achievements.repository.*;
import cn.btks.resultintegration.achievements.service.AchievementsService;
import cn.btks.resultintegration.achievements.service.EnvironmentAttributeService;
import cn.btks.resultintegration.achievements.service.TextAchievementsService;
import cn.btks.resultintegration.achievements.service.VectorFileCategoryService;
import cn.btks.resultintegration.catalog.pojo.Catalog;
import cn.btks.resultintegration.catalog.service.CatalogService;
import cn.btks.resultintegration.feign.FeignObject.Unit;
import com.alibaba.fastjson.JSON;
import com.supermap.data.*;
import com.supermap.data.conversion.DataImport;
import com.supermap.data.conversion.ImportResult;
import com.supermap.data.conversion.ImportSettingSHP;
import com.supermap.data.conversion.ImportSettings;
import com.supermap.data.topology.TopologyValidator;
import io.jsonwebtoken.Claims;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author lijun
 * @Date 2020/12/16 16:00
 */
@Service
@Transactional
public class AchievementsServiceImpl implements AchievementsService {

    @Autowired
    AchievementsRepository achievementsRepository;

    @Autowired
    AchievementsTypeRepository achievementsTypeRepository;

    @Autowired
    AchievementsFileRepository achievementsFileRepository;

    @Autowired
    CatalogService catalogService;

    @Autowired
    EnvironmentAttributeService environmentAttributeService;

    @Autowired
    VectorFileCategoryService vectorFileCategoryService;

    @Autowired
    TextAchievementsService textAchievementsService;

    @Autowired
    TextAchievementsRepository textAchievementsRepository;

    @Autowired
    LayerFeaturesRepository layerFeaturesRepository;

    @Autowired
    BaseAchievementsFileRepository baseAchievementsFileRepository;

    @Autowired
    EnvironmentAttributeRepository environmentAttributeRepository;

    @Override
    public List<Achievements> findAll() {
        return achievementsRepository.findAll();
    }

    @Override
    public Achievements findById(Long id) {
        Optional<Achievements> optional = achievementsRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    @Override
    public List<Achievements> findAllByAchievementsTypeId(Long achievementsTypeId) {
        return achievementsRepository.findAllByTypeId(achievementsTypeId);
    }

    @Override
    public List<Achievements> findAllByCatalogId(Long catalogId) {
        return achievementsRepository.findAllByCatalogId(catalogId);
    }

    @Override
    public List<Achievements> findAllByCatalogIds(List<Long> catalogIds) {
        List<Achievements> achievementsList = new ArrayList<>();
        if (catalogIds != null && catalogIds.size() > 0) {
            for (Long id : catalogIds) {
                List<Achievements> achievements = achievementsRepository.findAllByCatalogId(id);
                achievementsList.addAll(achievements);
            }
        }
        return achievementsList;
    }

    @Override
    public List<Achievements> findAllByCatalogIdAndAchievementsTypeId(Long catalogId, Long achievementsTypeId) {
        return achievementsRepository.findAllByCatalogIdAndTypeId(catalogId, achievementsTypeId);
    }

    @Override
    public List<Achievements> findAllByCatalogIdAndAchievementsTypeIds(List<Long> catalogIds, Long achievementsTypeId) {
        List<Achievements> achievementsList = new ArrayList<>();
        if (catalogIds != null && catalogIds.size() > 0) {
            for (Long id : catalogIds) {
                List<Achievements> achievements = achievementsRepository.findAllByCatalogIdAndTypeId(id, achievementsTypeId);
                achievementsList.addAll(achievements);
            }
        }
        return achievementsList;
    }

    @Override
    public ResultState findPage(Integer pageNumber, Integer pageSize, Integer isApproved) {
        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);
        Specification<Achievements> specification = new Specification<Achievements>() {
            @Override
            public Predicate toPredicate(Root<Achievements> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (isApproved != null) {
                    predicates.add(criteriaBuilder.equal(root.get("isApproved"), isApproved));
                }
                predicates.add(criteriaBuilder.equal(root.get("isHistory"), 0));
                Predicate[] predicates1 = new Predicate[predicates.size()];
                return criteriaBuilder.and(predicates.toArray(predicates1));
            }
        };
        Page<Achievements> configPage = achievementsRepository.findAll(specification, pageRequest);
        if (configPage.getTotalElements() > 0) {
            PageList pageList = new PageList();
            pageList.setResult(configPage.getContent());
            pageList.setPageNum(configPage.getTotalPages());
            pageList.setTotalCount(configPage.getTotalElements());
            return new ResultState(StateInfo.FIND_OK.getCode(), StateInfo.FIND_OK.getMsg(), pageList);
        }
        return new ResultState(StateInfo.FIND_NULL.getCode(), StateInfo.FIND_NULL.getMsg());
    }

    @Override
    public ResultState save(Achievements achievements, List<MultipartFile> multipartFiles, HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<>();
        List<EnvironmentAttribute> environmentAttributes = new ArrayList<>();
        List<AchievementsFile> achievementsFileList = new ArrayList<>();
        List<AchievementsType> achievementsTypes = achievementsTypeRepository.findAll();
        if (multipartFiles != null && multipartFiles.size() > 0) {
            Optional<AchievementsType> optional = achievementsTypes.stream().filter(s -> s.getId() == achievements.getTypeId()).findFirst();
            if (optional.isPresent()) {
                AchievementsType achievementsType = optional.get();
                String filePath = "";
                switch (achievementsType.getCode()) {
                    case "VECTOR":
                        filePath = Constants.ACHIEVEMENTS_VECTOR_FILE;
                        break;
                    case "TEXT":
                        filePath = Constants.ACHIEVEMENTS_TEXT_FILE;
                        break;
                    case "PICTURE":
                        filePath = Constants.ACHIEVEMENTS_PICTURE_FILE;
                        break;
                    case "REPORT":
                        filePath = Constants.ACHIEVEMENTS_REPORT_FILE;
                        break;
                }
                String fileServerPath = "";
                String uuid = UUID.randomUUID().toString();
                for (int i = 0; i < multipartFiles.size(); i++) {
                    AchievementsFile achievementsFile = new AchievementsFile();
                    String fjName = uuid + "_" + multipartFiles.get(i).getOriginalFilename();
                    String fileOriginalFileName = multipartFiles.get(i).getOriginalFilename();
                    String pathname = request.getSession(true).getServletContext().getRealPath("//") + filePath + fjName;
                    String filePathFinal = filePath + fjName;
                    System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                    if (FileUtil.fileUpload(multipartFiles.get(i), pathname)) {
                        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
                    }
                    String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
                    if (!StringUtils.isEmpty(suffix)) {
                        if (suffix.equals("shp")) {
                            //当为shp文件时，对其进行解析
                            fileServerPath = pathname;
                        }
                        achievementsFile.setFileType(suffix);
                    }
                    achievementsFile.setFilePath(filePathFinal);
                    achievementsFile.setFileName(fileOriginalFileName);
                    achievementsFile.setAchievementsTypeId(achievements.getTypeId());
                    achievementsFile.setIsHistory(0);
                    achievementsFileList.add(achievementsFile);
                    achievementsFile.setContent(achievements.getContent());
                }
                objectMap = analysisVector1(fileServerPath, achievements);
                achievements.setFiles(achievementsFileList);
                for (AchievementsFile file : achievementsFileList) {
                    file.setAchievements(achievements);
                }
            }
        }
        if (objectMap.containsKey("error")) {
            //审核不通过
            achievements.setIsApproved(0);
            List<String> errors = (List<String>) objectMap.get("error");
            String errorStr = "";
            for (String item : errors) {
                errorStr += item;
            }
            achievements.setVerifyContent(errorStr);
        } else {
            //审核中
            achievements.setIsApproved(2);
        }
        if (objectMap.containsKey("attribute")) {
            environmentAttributes = (List<EnvironmentAttribute>) objectMap.get("attribute");
        }
//        if (environmentAttributes == null || environmentAttributes.size() == 0) {
//            //审核不通过
//            achievements.setIsApproved(0);
//        } else {
//            //审核中
//            achievements.setIsApproved(2);
//        }
        Achievements achievements1 = achievementsRepository.save(achievements);
        if (achievements1 != null) {
            if (environmentAttributes != null || environmentAttributes.size() > 0) {
                for (EnvironmentAttribute item : environmentAttributes) {
                    item.setAchievementId(achievements1.getId());
                }
                environmentAttributeService.saveAll(environmentAttributes);
            }
        }
        return achievements1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), achievements1) :
                new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState save(Integer isLayerFeature, Achievements achievements, MultipartFile multipartTextFile, List<MultipartFile> multipartVectorFiles, List<MultipartFile> multipartEvidenceFiles, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Optional<Claims> optionalClaims = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
        if (optionalClaims.isPresent()) {
            Claims claims = optionalClaims.get();
            String userName = claims.get("username").toString();
            String unitName = claims.get("unitName").toString();
            Object obj = claims.get("unit");
            Unit unit = com.alibaba.fastjson.JSONArray.parseObject(JSON.toJSONString(obj), Unit.class);
            if (unit != null) {
                achievements.setUnitId(unit.getCityId());
            }
            achievements.setReportUser(userName);
            achievements.setReportUnit(unitName);
        }
        Map<String, Object> objectMap = new HashMap<>();
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> textResultMap = new HashMap<>();
        Map<String, Object> vectorResultMap = new HashMap<>();
        List<Map<String, Object>> vectorMapList = new ArrayList<>();
        List<Map<String, Object>> textMapList = new ArrayList<>();
        List<String> vectorResultList = new ArrayList<>();
        List<String> textResultList = new ArrayList<>();
        List<String> vectorSuccessResultList = new ArrayList<>();
        List<String> textSuccessResultList = new ArrayList<>();
        List<EnvironmentAttribute> environmentAttributes = new ArrayList<>();
        List<AchievementsFile> achievementsFileList = new ArrayList<>();
        List<TextAchievements> textAchievementsList = new ArrayList<>();
        List<AchievementsType> achievementsTypes = achievementsTypeRepository.findAll();
        AchievementsType achievementsVectorType = achievementsTypes.stream().filter(s -> s.getCode().equals("VECTOR")).findFirst().get();
        AchievementsType achievementsTextType = achievementsTypes.stream().filter(s -> s.getCode().equals("TEXT")).findFirst().get();
        AchievementsType achievementsEvidenceType = achievementsTypes.stream().filter(s -> s.getCode().equals("EVIDENCE")).findFirst().get();
        List<VectorFileCategory> vectorFileCategoryList = vectorFileCategoryService.findAll();
        if (multipartVectorFiles != null && multipartEvidenceFiles != null) {
            vectorResultMap.put("false", vectorResultList);
            textResultMap.put("false", textResultList);
            vectorResultMap.put("true", vectorSuccessResultList);
            textResultMap.put("true", textSuccessResultList);
            vectorMapList.add(vectorResultMap);
            textMapList.add(textResultMap);
            String fileVectorPath = Constants.ACHIEVEMENTS_VECTOR_FILE;
            String fileTextPath = Constants.ACHIEVEMENTS_TEXT_FILE;
            String fileEvidencePath = Constants.ACHIEVEMENTS_EVIDENCE_FILE;
            //保存管控单元清单文本文件
            if (multipartTextFile != null && isLayerFeature == 0) {
                textAchievementsList = analysisTextFile(fileTextPath, achievementsFileList, multipartTextFile, achievements, achievementsTextType, request);
                if (textAchievementsList != null && textAchievementsList.size() > 0) {

                } else {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                }
            }
            //保存矢量文件
            if (multipartVectorFiles != null) {
                achievements.setTypeId(achievementsVectorType.getId());
                String fileServerPath = "";
                String uuid = UUID.randomUUID().toString();
                List<AchievementsFile> achievementsFiles = new ArrayList<>();
                for (int i = 0; i < multipartVectorFiles.size(); i++) {
                    AchievementsFile achievementsFile = new AchievementsFile();
                    String fjName = uuid + "_" + multipartVectorFiles.get(i).getOriginalFilename();
                    String fileOriginalFileName = multipartVectorFiles.get(i).getOriginalFilename();
                    String pathname = request.getSession(true).getServletContext().getRealPath("//") + fileVectorPath + fjName;
                    String filePathFinal = fileVectorPath + fjName;
                    System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                    List<AchievementsFile> fileList = achievementsFileRepository.findAllByFileName(fileOriginalFileName);
                    if (fileList != null && fileList.size() > 0) {
                        return new ResultState(StateInfo.FILE_EXIST_ERROR.getCode(), StateInfo.FILE_EXIST_ERROR.getMsg());
                    }
                    if (FileUtil.fileUpload(multipartVectorFiles.get(i), pathname)) {
                        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
                    }
                    String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
                    if (!StringUtils.isEmpty(suffix)) {
                        if (suffix.equals("shp")) {
                            //当为shp文件时，对其进行解析
                            fileServerPath = pathname;
                        }
                        if (suffix.equals("prj")) {
                            BufferedReader bufferedReader = new BufferedReader(new FileReader(pathname));
                            String line = null;
                            String fileContent = "";
                            while ((line = bufferedReader.readLine()) != null) {
                                fileContent = line;
                            }
                            if (fileContent.contains("Coordinate System 2000")) {
                                vectorSuccessResultList.add("坐标系无误。");
                            } else {
                                vectorResultList.add("坐标系错误。");
                            }
                        }
                        achievementsFile.setFileType(suffix);
                    }
                    achievementsFile.setFilePath(filePathFinal);
                    achievementsFile.setFileName(fileOriginalFileName);
                    achievementsFile.setAchievementsTypeId(achievementsVectorType.getId());
                    achievementsFile.setIsHistory(0);
                    achievementsFiles.add(achievementsFile);
                    achievementsFile.setContent(achievements.getContent());
                }
                if (achievementsFiles.size() <= 0) {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                }
                objectMap = analysisVector1(fileServerPath, achievements);
                achievementsFileList.addAll(achievementsFiles);
                achievements.setFiles(achievementsFileList);
                for (AchievementsFile file : achievementsFileList) {
                    file.setAchievements(achievements);
                }
            } else {
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), "审核不通过，缺少矢量文件");
            }
            //佐证材料
            if (multipartEvidenceFiles != null) {
                String fileServerPath = "";
                List<AchievementsFile> achievementsFiles = new ArrayList<>();
                for (int i = 0; i < multipartEvidenceFiles.size(); i++) {
                    String uuid = UUID.randomUUID().toString();
                    AchievementsFile achievementsFile = new AchievementsFile();
                    String fjName = uuid + "_" + multipartEvidenceFiles.get(i).getOriginalFilename();
                    String fileOriginalFileName = multipartEvidenceFiles.get(i).getOriginalFilename();
                    String pathname = request.getSession(true).getServletContext().getRealPath("//") + fileEvidencePath + fjName;
                    String filePathFinal = fileEvidencePath + fjName;
                    System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                    if (FileUtil.fileUpload(multipartEvidenceFiles.get(i), pathname)) {
                        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                    }
                    String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
                    if (!StringUtils.isEmpty(suffix)) {
                        achievementsFile.setFileType(suffix);
                    }
                    achievementsFile.setFilePath(filePathFinal);
                    achievementsFile.setFileName(fileOriginalFileName);
                    achievementsFile.setAchievementsTypeId(achievementsEvidenceType.getId());
                    achievementsFile.setIsHistory(0);
                    achievementsFileList.add(achievementsFile);
                    achievementsFiles.add(achievementsFile);
                    achievementsFile.setContent(achievements.getContent());
                }
                if (achievementsFiles.size() <= 0) {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                }
                for (AchievementsFile file : achievementsFiles) {
                    file.setAchievements(achievements);
                }
                textSuccessResultList.add("具备佐证材料。");
            } else {
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), "审核不通过，缺少佐证材料文件");
            }
            if (objectMap.containsKey("error")) {
                //审核不通过
                achievements.setIsApproved(0);
                List<String> errors = (List<String>) objectMap.get("error");
                String errorStr = "矢量文件解析出错：";
                for (String item : errors) {
                    errorStr += item + "/r/n";
                }
                achievements.setVerifyContent(errorStr);
                vectorResultList.add("矢量文件解析错误：" + errorStr);
            } else {
                vectorSuccessResultList.add("矢量文件解析成功。");
            }
            if (objectMap.containsKey("attribute")) {
                //校验管控清单和矢量文件属性是否一一对应
                environmentAttributes = (List<EnvironmentAttribute>) objectMap.get("attribute");
                if (textAchievementsList.size() > 0) {
                    String hjgkdybm = "";
                    boolean isExist = false;
                    for (EnvironmentAttribute item : environmentAttributes) {
                        boolean result = textAchievementsList.stream().anyMatch(s -> s.getUnitCode().trim().equals(item.getHJDYBM()));
                        if (!result) {
                            isExist = true;
                            hjgkdybm += item.getHJDYBM() + "/";
                        }
                    }
                    if (isExist) {
                        textResultList.add("环境管控清单中的数据和矢量数据中的属性不是一一对应。编码：" + hjgkdybm);
                    } else {
                        textSuccessResultList.add("具备管控清单文件。");
                        textSuccessResultList.add("环境管控清单和矢量数据相匹配。");
                    }
                }
            }
            resultMap.put("TEXT", textMapList);
            resultMap.put("VECTOR", vectorMapList);
            if (textResultList.size() > 0 || vectorResultList.size() > 0) {
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
            }
            //审核中
            achievements.setIsApproved(2);
            achievements.setVerifyContent("系统审核通过");
            //矢量属性解析后数据
            if (objectMap.containsKey("attribute")) {
                environmentAttributes = (List<EnvironmentAttribute>) objectMap.get("attribute");
            }
            //保存文本清单数据
            if (textAchievementsList != null) {
                textAchievementsService.saveAll(textAchievementsList);
            }
            achievements.setUploadDate(new Date());
            achievements.setVerifyType(0);
            if (isLayerFeature == 0) {
                Catalog catalog = catalogService.findByCode("4");
                achievements.setCatalogId(catalog.getId());
            }
            achievements.setIsHistory(0);
            Achievements achievements1 = achievementsRepository.save(achievements);
            if (achievements1 != null) {
                if (environmentAttributes != null || environmentAttributes.size() > 0) {
                    for (EnvironmentAttribute item : environmentAttributes) {
                        item.setAchievementId(achievements1.getId());
                    }
                    environmentAttributeService.saveAll(environmentAttributes);
                }
            }
            return achievements1 != null ? new ResultState(StateInfo.SAVE_VERIFY_OK.getCode(), StateInfo.SAVE_VERIFY_OK.getMsg(), resultMap) :
                    new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), "保存成果失败");
        } else {
            textResultList.add("文件材料不完整");
            resultMap.put("TEXT", textResultList);
            //审核不通过
            return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
        }
    }

    @Override
    public ResultState saveZipFile(Achievements achievements, MultipartFile multipartFileZip, MultipartFile multipartTextFile, HttpServletRequest request) throws Exception {
        if (multipartFileZip != null && multipartTextFile != null) {
            String uuid = UUID.randomUUID().toString();
            String fjName = uuid + "_" + multipartFileZip.getOriginalFilename();
            String zipVectorFilePath = request.getSession(true).getServletContext().getRealPath("//") + Constants.ACHIEVEMENTS_ZIP_VECTOR_FILE + fjName;
            String zipTextFilePath = request.getSession(true).getServletContext().getRealPath("//") + Constants.ACHIEVEMENTS_ZIP_TEXT_FILE + fjName;
            if (FileUtil.fileUpload(multipartFileZip, zipVectorFilePath)) {
                return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
            }
            if (FileUtil.fileUpload(multipartTextFile, zipTextFilePath)) {
                return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
            }

            //解压
            List<File> zipUncompressVectorFiles = ZipMultiFile.zipTextUncompress(zipVectorFilePath);//解压矢量文件
            List<File> zipUncompressTextFiles = ZipMultiFile.zipTextUncompress(zipTextFilePath);//解压管控清单

            //审核结果对象
            List<Map<String, Object>> analysisResult = new ArrayList<>();//保存vector和text两者的解析失败原因
            Map<String, Object> analysisVectorItem = new HashMap<>();//保存矢量项的失败原因
            Map<String, Object> analysisTextItem = new HashMap<>();//保存管控清单的失败原因

            List<String> fileVectorErrorList = new ArrayList<>();//矢量-文件-相关错误信息
            analysisVectorItem.put("file", fileVectorErrorList);
            List<String> contentVectorErrorList = new ArrayList<>();//矢量-内容项-相关错误信息
            analysisVectorItem.put("content", contentVectorErrorList);
            List<String> spaceVectorErrorList = new ArrayList<>();//矢量-空间坐标系-相关错误信息
            analysisVectorItem.put("space", spaceVectorErrorList);
            List<String> topologyVectorErrorList = new ArrayList<>();//矢量-拓扑检查-相关错误信息
            analysisVectorItem.put("topology", topologyVectorErrorList);

            List<String> fileTextErrorList = new ArrayList<>();//管控清单-文件-相关错误信息
            analysisTextItem.put("file", fileTextErrorList);
            List<String> contentTextErrorList = new ArrayList<>();//管控清单-内容项-相关错误信息
            analysisTextItem.put("content", contentTextErrorList);

            List<TextAchievements> textAchievementsList = new ArrayList<>();//管控清单数据
            List<LayerFeatures> layerFeaturesList = new ArrayList<>();//环境要素清单数据
            List<EnvironmentAttribute> environmentAttributes = new ArrayList<>();//矢量解析数据
            List<EnvironmentAttribute> environmentAttributesDY = new ArrayList<>();//管控单元矢量解析数据
            List<EnvironmentAttribute> environmentAttributesYS = new ArrayList<>();//管控要素矢量解析数据

            //界面展示返回对象
            List<Map<String, Object>> shpAnalysisResults = new ArrayList<>();//所有shp解析后的结果，errors-attributes-attributeResult
            List<String> shpAnalysisErrorPaths = new ArrayList<>();//解析有问题的shp文件集合
            Map<String, Object> objectMap = new HashMap<>();
            Map<String, Object> resultMap = new HashMap<>();
            Map<String, Object> textResultMap = new HashMap<>();
            Map<String, Object> vectorResultMap = new HashMap<>();
            List<Map<String, Object>> vectorMapList = new ArrayList<>();
            List<Map<String, Object>> textMapList = new ArrayList<>();
            List<String> vectorResultList = new ArrayList<>();
            List<String> textResultList = new ArrayList<>();
            List<String> vectorSuccessResultList = new ArrayList<>();
            List<String> textSuccessResultList = new ArrayList<>();

            //审核结果
            vectorResultMap.put("false", vectorResultList);
            textResultMap.put("false", textResultList);
            vectorResultMap.put("true", vectorSuccessResultList);
            textResultMap.put("true", textSuccessResultList);
            vectorMapList.add(vectorResultMap);
            textMapList.add(textResultMap);

            //保存成果数据对象
            List<AchievementsFile> achievementsFileList = new ArrayList<>();
            List<Achievements> achievementsList = new ArrayList<>();

            //文件保存路径
            String fileVectorPath = Constants.ACHIEVEMENTS_VECTOR_FILE;
            String fileTextPath = Constants.ACHIEVEMENTS_TEXT_FILE;
            String fileEvidencePath = Constants.ACHIEVEMENTS_EVIDENCE_FILE;

            //导出报告模板及导出文件路径
            String verifyTemplateFile = "/res/achievements/verify/template/VerifyTemplate.docx";//模板
            String verifyFile = request.getSession(true).getServletContext().getRealPath("//") + Constants.ACHIEVEMENTS_ANALYSIS_FILE + "VerifyFile.docx";//生成报告
            String templateDirPath = request.getSession(true).getServletContext().getRealPath("//") + Constants.ACHIEVEMENTS_ANALYSIS_FILE;
            String returnFilePath = Constants.ACHIEVEMENTS_ANALYSIS_FILE + "VerifyFile.docx";//生成报告
            File fileTemplateDir = new File(templateDirPath);
            if (!fileTemplateDir.exists()) {
                fileTemplateDir.mkdirs();
            }

            //文件命名规范
            List<VectorFileCategory> vectorFileCategories = vectorFileCategoryService.findAll();

            //成果类型
            List<AchievementsType> achievementsTypes = achievementsTypeRepository.findAll();
            AchievementsType achievementsVectorType = achievementsTypes.stream().filter(s -> s.getCode().equals("VECTOR")).findFirst().get();
            AchievementsType achievementsTextType = achievementsTypes.stream().filter(s -> s.getCode().equals("TEXT")).findFirst().get();

            //初始化审核参数为√
            VerifyParamDto verifyParamDto = new VerifyParamDto("√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√", "√");

            String userName = "";
            String unitName = "";
            Long unitId = Long.valueOf(0);
            String token = request.getHeader("token");
            Optional<Claims> optionalClaims = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
            if (optionalClaims.isPresent()) {
                Claims claims = optionalClaims.get();
                userName = claims.get("username").toString();
                unitName = claims.get("unitName").toString();
                Object obj = claims.get("unit");
                Unit unit = com.alibaba.fastjson.JSONArray.parseObject(JSON.toJSONString(obj), Unit.class);
                if (unit != null) {
                    unitId = unit.getCityId();
                }
            }

            //矢量文件
            if (!zipUncompressVectorFiles.isEmpty()) {
                List<File> shapeFiles = zipUncompressVectorFiles.stream().filter(s -> s.getPath().substring(s.getPath().lastIndexOf(".") + 1).equals("shp")).collect(Collectors.toList());
                if (shapeFiles == null || shapeFiles.isEmpty()) {
                    verifyParamDto.setVectorZip("×");
                    verifyParamDto.setVectorTopologyError("×");
                    verifyParamDto.setVectorSpaceError("×");
                    verifyParamDto.setVectorContentError("×");
                    verifyParamDto.setVectorLayerName("×");
                    verifyParamDto.setVectorSuffix("×");
                    verifyParamDto.setVectorCode("×");
                    verifyParamDto.setVectorCoor("×");
                    verifyParamDto.setVectorFileName("×");
                    verifyParamDto.setVectorFileError("×");
                    verifyParamDto.setAttributeContent("×");
                    verifyParamDto.setAttributeLength("×");
                    verifyParamDto.setAttributeComplete("×");
                    verifyParamDto.setLayerType("×");
                }
                //一、文件审核
                //文件可以正常解压,判定文件命名
                if (vectorFileCategories != null && !vectorFileCategories.isEmpty()) {
                    List<String> fileServerPathList = new ArrayList<>();//shp文件路径
                    for (VectorFileCategory categoryItem : vectorFileCategories) {
                        String vectorFileName = categoryItem.getVectorName();//矢量文件标准名称
                        List<File> collect = zipUncompressVectorFiles.stream().filter(s -> s.getName().substring(0, s.getName().indexOf(".")).equals(vectorFileName)).collect(Collectors.toList());
                        if (collect != null && !collect.isEmpty()) {
                            //保存矢量文件
                            Achievements achievementsTemp = new Achievements();
                            achievementsTemp.setTypeId(achievementsVectorType.getId());
                            achievementsTemp.setIsHistory(0);
                            achievementsTemp.setIsApproved(2);
                            achievementsTemp.setUploadDate(new Date());
                            achievementsTemp.setVerifyType(0);
                            achievementsTemp.setReportUser(userName);
                            achievementsTemp.setReportUnit(unitName);
                            achievementsTemp.setUnitId(unitId);
                            List<AchievementsFile> achievementsFiles = new ArrayList<>();
                            for (File fileItem : collect) {
                                AchievementsFile achievementsFile = new AchievementsFile();
                                String fileName = fileItem.getName();
                                String fileName1 = fileName.substring(0, fileName.indexOf("."));
                                String filePath = fileItem.getPath();
                                String absolutePath = fileItem.getAbsolutePath();
                                String pathname = request.getSession(true).getServletContext().getRealPath("//") + fileVectorPath + fileName;
                                String filePathFinal = fileVectorPath + fileName;
                                System.out.println(request.getSession(true).getServletContext().getRealPath("//"));

                                //拷贝文件
                                FileUtils.copyFile(fileItem, new File(pathname));

                                String suffix = filePath.substring(filePath.lastIndexOf(".") + 1);
                                if (!StringUtils.isEmpty(suffix)) {
                                    if (suffix.equals("shp")) {
                                        //当为shp文件时，对其进行解析
                                        fileServerPathList.add(pathname);
                                        //解析shp文件
                                        objectMap = analysisVector1(pathname, fileName1, achievementsTemp);
                                        shpAnalysisResults.add(objectMap);
                                        if (objectMap.containsKey("error")) {
                                            //未通过的shp列表
                                            shpAnalysisErrorPaths.add(fileName);
                                        }
                                        if (objectMap.containsKey("attribute")) {
                                            environmentAttributes.addAll((List<EnvironmentAttribute>) objectMap.get("attribute"));
                                            if (fileName1.equals("IntergratedControlUnit兵团")) {
                                                Catalog catalog = catalogService.findByCode("4");
                                                achievementsTemp.setCatalogId(catalog.getId());
                                            }
                                        }
                                        if (objectMap.containsKey("attributeYS")) {
                                            environmentAttributesYS.addAll((List<EnvironmentAttribute>) objectMap.get("attributeYS"));
                                        }
                                        if (objectMap.containsKey("attributeDY")) {
                                            environmentAttributesDY.addAll((List<EnvironmentAttribute>) objectMap.get("attributeDY"));
                                        }
                                    }
                                    if (suffix.equals("prj")) {
                                        BufferedReader bufferedReader = new BufferedReader(new FileReader(pathname));
                                        String line = null;
                                        String fileContent = "";
                                        while ((line = bufferedReader.readLine()) != null) {
                                            fileContent = line;
                                        }
                                        if (fileContent.contains("Coordinate System 2000")) {
                                            vectorSuccessResultList.add("坐标系无误。");
                                        } else {
                                            spaceVectorErrorList.add("平面基准未采用2000国家大地坐标系（CGCS2000）");
                                            vectorResultList.add("坐标系错误。");
                                            verifyParamDto.setVectorCoor("×");
                                        }
                                    }
                                    achievementsFile.setFileType(suffix);
                                }

                                achievementsFile.setFilePath(filePathFinal);
                                achievementsFile.setFileName(fileName);
                                achievementsFile.setAchievementsTypeId(achievementsVectorType.getId());
                                achievementsFile.setIsHistory(0);
                                achievementsFiles.add(achievementsFile);
                                achievementsFile.setContent(achievementsTemp.getContent());
                                achievementsFile.setAchievements(achievementsTemp);
                                achievementsList.add(achievementsTemp);
                            }
                            achievementsTemp.setFiles(achievementsFiles);
                        }
                    }

                    //文件命名是否正确
                    String fileNameError = "";
                    for (File fileItem : zipUncompressVectorFiles) {
                        String fileName = fileItem.getName();
                        String fileName1 = fileName.substring(0, fileName.indexOf("."));
                        Optional<VectorFileCategory> optional = vectorFileCategories.stream().filter(s -> s.getVectorName().equals(fileName1)).findFirst();
                        if (!optional.isPresent()) {
                            fileNameError += fileName + "/";
                        } else {
                            VectorFileCategory vectorFileCategory = optional.get();
                            String item = vectorFileCategory.getVectorName();
                            if (!item.equals(fileName1)) {
                                fileNameError += fileName + "/";
                            }
                        }
                    }
                    if (!StringUtils.isEmpty(fileNameError)) {
                        fileVectorErrorList.add("文件命名有误：" + fileNameError);
                        verifyParamDto.setVectorFileName("×");
                        verifyParamDto.setVectorLayerName("×");
                    }

                    //批量解析矢量文件
                    if (fileServerPathList.isEmpty() || fileServerPathList.size() != 21) {
                        contentVectorErrorList.add("shp图层文件不完整。");
                        verifyParamDto.setVectorSuffix("×");
                    }

                    //二、矢量审核
                    //针对解析的矢量进行报告填充
                    for (Map<String, Object> shpAnalysisItem : shpAnalysisResults) {
                        if (shpAnalysisItem.containsKey("error")) {
                            //审核不通过
//                        contentVectorErrorList
                            Map<String, Object> analysisAttributeMap = (Map<String, Object>) shpAnalysisItem.get("attributeResult");
                            if (MapUtils.isNotEmpty(analysisAttributeMap)) {
                                //属性项是否完整
                                if (analysisAttributeMap.containsKey("attributeComplete")) {
                                    List<String> attributeComplete = (List<String>) analysisAttributeMap.get("attributeComplete");
                                    if (attributeComplete != null && !attributeComplete.isEmpty()) {
                                        verifyParamDto.setAttributeComplete("×");
                                        contentVectorErrorList.addAll(attributeComplete);
                                    }
                                }
                                //类型长度是否正确
                                if (analysisAttributeMap.containsKey("attributeLength")) {
                                    List<String> attributeLength = (List<String>) analysisAttributeMap.get("attributeLength");
                                    if (attributeLength != null && !attributeLength.isEmpty()) {
                                        verifyParamDto.setAttributeLength("×");
                                        contentVectorErrorList.addAll(attributeLength);
                                    }
                                }
                                //内容值是否正确
                                if (analysisAttributeMap.containsKey("attributeContent")) {
                                    List<String> attributeContent = (List<String>) analysisAttributeMap.get("attributeContent");
                                    if (attributeContent != null && !attributeContent.isEmpty()) {
                                        verifyParamDto.setAttributeContent("×");
                                        contentVectorErrorList.addAll(attributeContent);
                                    }
                                }
                                //编码是否规范
                                if (analysisAttributeMap.containsKey("attributeCode")) {
                                    List<String> attributeCode = (List<String>) analysisAttributeMap.get("attributeCode");
                                    if (attributeCode != null && !attributeCode.isEmpty()) {
                                        verifyParamDto.setVectorCode("×");
                                        contentVectorErrorList.addAll(attributeCode);
                                    }
                                }
                            }
                        } else {
                            //审核通过
                        }
                    }
                }
            } else {
                verifyParamDto.setVectorZip("×");
                verifyParamDto.setVectorTopologyError("×");
                verifyParamDto.setVectorSpaceError("×");
                verifyParamDto.setVectorContentError("×");
                verifyParamDto.setVectorLayerName("×");
                verifyParamDto.setVectorSuffix("×");
                verifyParamDto.setVectorCode("×");
                verifyParamDto.setVectorCoor("×");
                verifyParamDto.setVectorFileName("×");
                verifyParamDto.setVectorFileError("×");
            }

            String topologyUDBXFile = "/res/achievements/topologyUDBX.udbx";
            String serverPath = this.getClass().getResource(topologyUDBXFile).getPath();
            serverPath = serverPath.substring(serverPath.indexOf("/") + 1, serverPath.length());
            String shpFilePath = request.getSession(true).getServletContext().getRealPath("//") + fileVectorPath;
            init(serverPath, shpFilePath);//初始化数据源

            //拓扑检查
            String vectorPath = request.getSession(true).getServletContext().getRealPath("//") + fileVectorPath;
            File dirFile = new File(vectorPath);
            if (dirFile.exists()) {
                File[] files = dirFile.listFiles();
                if (files.length > 0) {
                    //1、生态保护红线、一般生态空间及生态空间一般管控区图层是否存在重叠
//                    boolean ecoResult1 = topologyAnalysis("EcoRedline兵团", "EcoGenSpace兵团");
//                    boolean ecoResult2 = topologyAnalysis("EcoRedline兵团", "EcoGen兵团");
//                    boolean ecoResult3 = topologyAnalysis("EcoGenSpace兵团", "EcoGen兵团");
//                    if (ecoResult1 || ecoResult2 || ecoResult3) {
//                        verifyParamDto.setTopologyTopology1("×");
//                        topologyVectorErrorList.add("EcoRedline兵团、EcoGenSpace兵团、EcoGen兵团，三者存在图层重叠！");
//                    }
                    String ecoResult1 = topologyAnalysis1("EcoRedline兵团", "EcoGenSpace兵团");
                    String ecoResult2 = topologyAnalysis1("EcoRedline兵团", "EcoGen兵团");
                    String ecoResult3 = topologyAnalysis1("EcoGenSpace兵团", "EcoGen兵团");
                    if (!StringUtils.isEmpty(ecoResult1)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("EcoRedline兵团、EcoGenSpace兵团存在图层重叠！" + "重叠图斑：" + ecoResult1);
                    }
                    if (!StringUtils.isEmpty(ecoResult2)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("EcoRedline兵团、EcoGen兵团存在图层重叠！" + "重叠图斑：" + ecoResult2);
                    }
                    if (!StringUtils.isEmpty(ecoResult3)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("EcoGenSpace兵团、EcoGen兵团存在图层重叠！" + "重叠图斑：" + ecoResult3);
                    }

                    //2、水要素优先管控区、重点管控区图层并集边界（水环境工业污染重点管控区、城镇生活污染重点管控区、其他水环境重点管控区）、一般管控区三者是否存在重叠
//                    boolean hydroKeyResult1 = topologyAnalysis("HydroKeyIndustry兵团", "HydroKeyUrban兵团");
//                    boolean hydroKeyResult2 = topologyAnalysis("HydroKeyIndustry兵团", "HydroKeyOther兵团");
//                    boolean hydroKeyResult3 = topologyAnalysis("HydroKeyUrban兵团", "HydroKeyOther兵团");
//                    if (hydroKeyResult1 || hydroKeyResult2 || hydroKeyResult3) {
//                        verifyParamDto.setTopologyTopology2("×");
//                        topologyVectorErrorList.add("HydroKeyIndustry兵团、HydroKeyUrban兵团、HydroKeyOther兵团，三者存在图层重叠！");
//                    }
                    String hydroKeyResult1 = topologyAnalysis1("HydroKeyIndustry兵团", "HydroKeyUrban兵团");
                    String hydroKeyResult2 = topologyAnalysis1("HydroKeyIndustry兵团", "HydroKeyOther兵团");
                    String hydroKeyResult3 = topologyAnalysis1("HydroKeyUrban兵团", "HydroKeyOther兵团");
                    if (!StringUtils.isEmpty(hydroKeyResult1)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("HydroKeyIndustry兵团、HydroKeyUrban兵团存在图层重叠！" + "重叠图斑：" + hydroKeyResult1);
                    }
                    if (!StringUtils.isEmpty(hydroKeyResult2)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("HydroKeyIndustry兵团、HydroKeyOther兵团存在图层重叠！" + "重叠图斑：" + hydroKeyResult2);
                    }
                    if (!StringUtils.isEmpty(hydroKeyResult3)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("HydroKeyUrban兵团、HydroKeyOther兵团存在图层重叠！" + "重叠图斑：" + hydroKeyResult3);
                    }
                    //3、大气要素优先管控区、重点管控区图层并集边界（大气高排放重点管控区、布局敏感重点管控区、弱扩散重点管控区、受体敏感重点管控区、其他大气重点管控区）、一般管控区三者是否存在重叠
//                    boolean atomsResult1 = topologyAnalysis("AtomsPriority兵团", "AtomsGen兵团");
//                    boolean atomsResult2 = topologyAnalysis("AtomsPriority兵团", "AtomsKeyHighEmission兵团");
//                    boolean atomsResult3 = topologyAnalysis("AtomsGen兵团", "AtomsKeyHighEmission兵团");
//                    if (atomsResult1 || atomsResult2 || atomsResult3) {
//                        verifyParamDto.setTopologyTopology3("×");
//                        topologyVectorErrorList.add("AtomsPriority兵团、AtomsGen兵团、AtomsKeyHighEmission兵团，三者存在图层重叠！");
//                    }
                    String atomsResult1 = topologyAnalysis1("AtomsPriority兵团", "AtomsGen兵团");
                    String atomsResult2 = topologyAnalysis1("AtomsPriority兵团", "AtomsKeyHighEmission兵团");
                    String atomsResult3 = topologyAnalysis1("AtomsGen兵团", "AtomsKeyHighEmission兵团");
                    if (!StringUtils.isEmpty(atomsResult1)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("AtomsPriority兵团、AtomsGen兵团存在图层重叠！" + "重叠图斑：" + atomsResult1);
                    }
                    if (!StringUtils.isEmpty(atomsResult2)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("AtomsPriority兵团、AtomsKeyHighEmission兵团存在图层重叠！" + "重叠图斑：" + atomsResult2);
                    }
                    if (!StringUtils.isEmpty(atomsResult3)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("AtomsGen兵团、AtomsKeyHighEmission兵团存在图层重叠！" + "重叠图斑：" + atomsResult3);
                    }
                    //4、土壤优先管控区、土壤重点管控区并集边界（农用地污染风险重点管控区、建设用地污染风险重点管控区、其他土壤重点管控区）、一般管控区三者是否存在重叠

                    //5、自然资源重点管控区图层并集边界（生态用水补给区、地下水开采重点管控区、土地资源重点管控区、高污染燃料禁燃区、自然资源重点管控区、其他自然资源重点管控区）与一般管控区是否存在重叠
//                    boolean nRKeyResult1 = topologyAnalysis("NRKeyEcoWaterSupply兵团", "NRGen兵团");
//                    boolean nRKeyResult2 = topologyAnalysis("NRKeyGroundWaterExploKey兵团", "NRGen兵团");
//                    boolean nRKeyResult3 = topologyAnalysis("NRKeyLandReourceKey兵团", "NRGen兵团");
//                    boolean nRKeyResult4 = topologyAnalysis("NRKeyHighPolluFuelForbidv兵团", "NRGen兵团");
//                    if (nRKeyResult1 || nRKeyResult2 || nRKeyResult3 || nRKeyResult4) {
//                        verifyParamDto.setTopologyTopology5("×");
//                        topologyVectorErrorList.add("NRKeyEcoWaterSupply兵团、NRGen兵团、NRKeyGroundWaterExploKey兵团、NRKeyHighPolluFuelForbidv兵团，四者存在图层重叠！");
//                    }
                    String nRKeyResult1 = topologyAnalysis1("NRKeyEcoWaterSupply兵团", "NRGen兵团");
                    String nRKeyResult2 = topologyAnalysis1("NRKeyGroundWaterExploKey兵团", "NRGen兵团");
                    String nRKeyResult3 = topologyAnalysis1("NRKeyLandReourceKey兵团", "NRGen兵团");
                    String nRKeyResult4 = topologyAnalysis1("NRKeyHighPolluFuelForbidv兵团", "NRGen兵团");
                    if (!StringUtils.isEmpty(nRKeyResult1)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("NRKeyEcoWaterSupply兵团、NRGen兵团存在图层重叠！" + "重叠图斑：" + nRKeyResult1);
                    }
                    if (!StringUtils.isEmpty(nRKeyResult2)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("NRKeyGroundWaterExploKey兵团、NRGen兵团存在图层重叠！" + "重叠图斑：" + nRKeyResult2);
                    }
                    if (!StringUtils.isEmpty(nRKeyResult3)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("NRKeyLandReourceKey兵团、NRGen兵团存在图层重叠！" + "重叠图斑：" + nRKeyResult3);
                    }
                    if (!StringUtils.isEmpty(nRKeyResult4)) {
                        verifyParamDto.setTopologyTopology1("×");
                        topologyVectorErrorList.add("NRKeyHighPolluFuelForbidv兵团、NRGen兵团存在图层重叠！" + "重叠图斑：" + nRKeyResult4);
                    }
                } else {
                    verifyParamDto.setTopologyTopology1("×");
                    verifyParamDto.setTopologyTopology2("×");
                    verifyParamDto.setTopologyTopology3("×");
                    verifyParamDto.setTopologyTopology4("×");
                    verifyParamDto.setTopologyTopology5("×");
                    topologyVectorErrorList.add("矢量文件有误！");
                }
            } else {
                verifyParamDto.setTopologyTopology1("×");
                verifyParamDto.setTopologyTopology2("×");
                verifyParamDto.setTopologyTopology3("×");
                verifyParamDto.setTopologyTopology4("×");
                verifyParamDto.setTopologyTopology5("×");
                topologyVectorErrorList.add("矢量文件有误！");
            }

            //管控清单和环境要素管控文件
            if (!zipUncompressTextFiles.isEmpty()) {
                if (vectorFileCategories != null && !vectorFileCategories.isEmpty()) {
                    String fileNameError = "";
                    List<LayerFeatures> layerFeaturesListTemp = new ArrayList<>();//环境要素清单数据
                    for (File fileItem : zipUncompressTextFiles) {
                        //判定文件命名规范
                        String fileName = fileItem.getName();
                        String fileName1 = fileName.substring(0, fileName.indexOf("."));
                        Optional<VectorFileCategory> optional = vectorFileCategories.stream().filter(s -> s.getGkyqName().equals(fileName1)).findFirst();
                        if (!optional.isPresent()) {
                            fileNameError += fileName + "/";
                        }
                        //保存文件
                        String filePath = fileItem.getPath();
                        String absolutePath = fileItem.getAbsolutePath();
                        String pathname = request.getSession(true).getServletContext().getRealPath("//") + fileTextPath + fileName;
                        String filePathFinal = fileTextPath + fileName;
                        System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                        List<AchievementsFile> fileList = achievementsFileRepository.findAllByFileName(fileName);
                        if (fileList != null && fileList.size() > 0) {
                            return new ResultState(StateInfo.FILE_EXIST_ERROR.getCode(), StateInfo.FILE_EXIST_ERROR.getMsg());
                        }
                        //拷贝文件
                        FileUtils.copyFile(fileItem, new File(pathname));

                        String suffix = filePath.substring(filePath.lastIndexOf(".") + 1);
                        if (!StringUtils.isEmpty(suffix)) {
                            if (suffix.equals("xlsx")) {
                                if (fileName1.equals("兵团生态环境准入清单--环境管控单元")) {
                                    textAchievementsList = analysisTextFile1(filePath);//解析管控单元
                                    if (!textAchievementsList.isEmpty() && !environmentAttributesDY.isEmpty()) {
                                        String hjgkdybm = "";
                                        boolean isExist = false;
                                        List<String> hjgkdybmList = new ArrayList<>();
                                        for (EnvironmentAttribute item : environmentAttributesDY) {
                                            boolean result = textAchievementsList.stream().anyMatch(s -> s.getUnitCode().trim().equals(item.getHJDYBM()));
                                            if (!result) {
                                                isExist = true;
                                                if (!hjgkdybmList.contains(hjgkdybm)) {
                                                    hjgkdybm += item.getHJDYBM() + "/";
                                                    hjgkdybmList.add(hjgkdybm);
                                                }
                                            }
                                        }
                                        if (isExist) {
                                            String hjgkdybmStr = "";
                                            for (String item : hjgkdybmList) {
                                                hjgkdybmStr += item;
                                            }
                                            contentTextErrorList.add("环境管控清单中的数据和矢量数据中的属性不是一一对应。编码：" + hjgkdybmStr);
                                            textResultList.add("环境管控清单中的数据和矢量数据中的属性不是一一对应。编码：" + hjgkdybmStr);
                                            verifyParamDto.setOneToOne("×");
                                        } else {
                                            textSuccessResultList.add("具备管控清单文件。");
                                            textSuccessResultList.add("环境管控清单和矢量数据相匹配。");
                                        }
                                    } else {
                                        contentTextErrorList.add("环境管控清单中的数据不正确");
                                        verifyParamDto.setTextContent("×");
                                        verifyParamDto.setTextRequired("×");
                                    }
                                } else {
//                                    //环境要素管控要求
//                                    layerFeaturesListTemp = analysisLayerFeatureTextFile(filePath);
//                                    if (layerFeaturesListTemp.isEmpty()) {
//                                        contentTextErrorList.add("环境管控清单中的数据不正确");
//                                        verifyParamDto.setTextContent("×");
//                                        verifyParamDto.setTextRequired("×");
//                                    } else {
//                                        layerFeaturesList.addAll(layerFeaturesListTemp);
//                                    }
                                }
                            } else {
                                fileTextErrorList.add("文件扩展名有误。");
                                verifyParamDto.setTextForm("×");
                            }
                        }
                    }
                    if (!StringUtils.isEmpty(fileNameError)) {
                        fileTextErrorList.add("文件命名有误：" + fileNameError);
                        verifyParamDto.setTextFileName("×");
                        verifyParamDto.setTextSpace("×");

                    }
//                    if (zipUncompressTextFiles.size() != 21) {
//                        fileTextErrorList.add("管控清单及要素清单文件不完整");
//                        verifyParamDto.setTextFileName("×");
//                        verifyParamDto.setTextSpace("×");
//                    }
                }

            } else {
                verifyParamDto.setTextFileError("×");
                verifyParamDto.setTextContent("×");
                verifyParamDto.setTextSpace("×");
                verifyParamDto.setTextFileName("×");
                verifyParamDto.setTextRequired("×");
                verifyParamDto.setTextForm("×");
                verifyParamDto.setTextContentError("×");
            }

            //不存在审核报错，更新之前的矢量为历史数据，删除之前的属性信息
            if (fileVectorErrorList.isEmpty() && contentVectorErrorList.isEmpty() && spaceVectorErrorList.isEmpty() && topologyVectorErrorList.isEmpty() && fileTextErrorList.isEmpty() && contentTextErrorList.isEmpty()) {

                //更新之前的矢量成果为历史数据
                int updateHistoryResult = achievementsRepository.updateIsHistoryByTypeId(achievementsVectorType.getId(), achievementsTextType.getId(), 1);

                //将更新前的矢量\清单文件置为历史数据
                int updateHistoryResult1 = achievementsFileRepository.updateFileIsHistoryByTypeId(achievementsVectorType.getId(), achievementsTextType.getId(), 1);

                //保存矢量文件
                achievementsList.forEach(s->{
                    s.setVerifyContent("系统审核通过");
                });
                List<Achievements> achievementsList1 = achievementsRepository.saveAll(achievementsList);
                if (achievementsList1 != null && !achievementsList1.isEmpty()) {
                    //更新矢量属性数据：先删除之前的数据，再保存
                    environmentAttributeRepository.deleteAll();
                    List<AchievementsFile> intergratedControlUnitFiles = achievementsFileRepository.findAllByFileName("IntergratedControlUnit兵团.shp");
                    if (intergratedControlUnitFiles != null && !intergratedControlUnitFiles.isEmpty()) {
                        if (environmentAttributes != null || environmentAttributes.size() > 0) {
                            AchievementsFile achievementsFile = intergratedControlUnitFiles.get(0);
                            for (EnvironmentAttribute item : environmentAttributes) {
                                item.setAchievementId(achievementsFile.getAchievements().getId());
                            }
                            environmentAttributeService.saveAll(environmentAttributes);
                        }
                    }
                    //删除所有管控清单数据，再更新
                    textAchievementsRepository.deleteAll();
                    if (!textAchievementsList.isEmpty()) {
                        textAchievementsService.saveAll(textAchievementsList);
                    }
                    //删除所有管控要素，再更新
                    layerFeaturesRepository.deleteAllFeatures();
                    if (!layerFeaturesList.isEmpty()) {
                        layerFeaturesRepository.saveAll(layerFeaturesList);
                    }
                    verifyParamDto.setResult("审核通过");
                }
            } else {
                //填充模板报错信息
                if (!fileVectorErrorList.isEmpty()) {
                    String fileVectorError = "";
                    for (int i = 0; i < fileVectorErrorList.size(); i++) {
                        fileVectorError += "(" + String.valueOf(i + 1) + ")" + fileVectorErrorList.get(i) + "\r";
                    }
                    verifyParamDto.setVectorFileError(fileVectorError);
                }
                if (!contentVectorErrorList.isEmpty()) {
                    String contentVectorError = "";
                    for (int i = 0; i < contentVectorErrorList.size(); i++) {
                        contentVectorError += "(" + String.valueOf(i + 1) + ")" + contentVectorErrorList.get(i) + "\r";
                    }
                    verifyParamDto.setVectorContentError(contentVectorError);
                }
                if (!spaceVectorErrorList.isEmpty()) {
                    String spaceVectorError = "";
                    for (int i = 0; i < spaceVectorErrorList.size(); i++) {
                        spaceVectorError += "(" + String.valueOf(i + 1) + ")" + spaceVectorErrorList.get(i) + "\r";
                    }
                    verifyParamDto.setVectorSpaceError(spaceVectorError);
                }
                if (!topologyVectorErrorList.isEmpty()) {
                    String topologyVectorError = "";
                    for (int i = 0; i < topologyVectorErrorList.size(); i++) {
                        topologyVectorError += "(" + String.valueOf(i + 1) + ")" + topologyVectorErrorList.get(i) + "\r";
                    }
                    verifyParamDto.setVectorTopologyError(topologyVectorError);
                }
                if (!fileTextErrorList.isEmpty()) {
                    String fileTextError = "";
                    for (int i = 0; i < fileTextErrorList.size(); i++) {
                        fileTextError += "(" + String.valueOf(i + 1) + ")" + fileTextErrorList.get(i) + "\r";
                    }
                    verifyParamDto.setTextFileError(fileTextError);
                }
                if (!contentTextErrorList.isEmpty()) {
                    String contentTextError = "";
                    for (int i = 0; i < contentTextErrorList.size(); i++) {
                        contentTextError += "(" + String.valueOf(i + 1) + ")" + contentTextErrorList.get(i) + "\r";
                    }
                    verifyParamDto.setTextContentError(contentTextError);
                }
                verifyParamDto.setResult("未通过");
            }

            SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期格式
            String time = sformat.format(new Date());
            verifyParamDto.setAnalysisDate(time);
            //生成审核报告
            Map<String, Object> contentMap = new HashMap<>();
            contentMap.put("verify", verifyParamDto);
            InputStream inputStream = this.getClass().getResourceAsStream(verifyTemplateFile);
            PoitlUtil.GenerateTemplate1(inputStream, verifyFile, contentMap);

            return new ResultState(StateInfo.SAVE_VERIFY_OK.getCode(), StateInfo.SAVE_VERIFY_OK.getMsg(), returnFilePath);
        }
        return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg());
    }

    @Override
    public ResultState update(Achievements achievements, List<MultipartFile> multipartFiles, HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<>();
        List<EnvironmentAttribute> environmentAttributes = new ArrayList<>();
        List<AchievementsFile> achievementsFileList = new ArrayList<>();
        List<AchievementsType> achievementsTypes = achievementsTypeRepository.findAll();
        if (multipartFiles != null && multipartFiles.size() > 0) {
            Optional<AchievementsType> optional = achievementsTypes.stream().filter(s -> s.getId() == achievements.getTypeId()).findFirst();
            if (optional.isPresent()) {
                AchievementsType achievementsType = optional.get();
                String filePath = "";
                switch (achievementsType.getCode()) {
                    case "VECTOR":
                        filePath = Constants.ACHIEVEMENTS_VECTOR_FILE;
                        break;
                    case "TEXT":
                        filePath = Constants.ACHIEVEMENTS_TEXT_FILE;
                        break;
                    case "PICTURE":
                        filePath = Constants.ACHIEVEMENTS_PICTURE_FILE;
                        break;
                    case "REPORT":
                        filePath = Constants.ACHIEVEMENTS_REPORT_FILE;
                        break;
                }
                String fileServerPath = "";
                String uuid = UUID.randomUUID().toString();
                for (int i = 0; i < multipartFiles.size(); i++) {
                    AchievementsFile achievementsFile = new AchievementsFile();
                    String fjName = uuid + "_" + multipartFiles.get(i).getOriginalFilename();
                    String fileOriginalFileName = multipartFiles.get(i).getOriginalFilename();
                    String pathname = request.getSession(true).getServletContext().getRealPath("//") + filePath + fjName;
                    fileServerPath = pathname;
                    String filePathFinal = filePath + fjName;
                    System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                    if (FileUtil.fileUpload(multipartFiles.get(i), pathname)) {
                        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
                    }
                    String[] split = filePathFinal.split(".");
                    if (split != null && split.length > 0) {
                        int length = split.length;
                        String type = split[length - 1];
                        if (!StringUtils.isEmpty(type)) {
                            if (type.equals("shp")) {
                                //当为shp文件时，对其进行解析
                                fileServerPath = pathname;
                            }
                            achievementsFile.setFileType(type);
                        }
                    }
                    achievementsFile.setFilePath(filePathFinal);
                    achievementsFile.setFileName(fileOriginalFileName);
                    achievementsFile.setAchievementsTypeId(achievements.getTypeId());
                    achievementsFileList.add(achievementsFile);
                }
                objectMap = analysisVector1(fileServerPath, achievements);
                achievements.setFiles(achievementsFileList);
                for (AchievementsFile file : achievementsFileList) {
                    file.setAchievements(achievements);
                }
            }
        }
        if (objectMap.containsKey("error")) {
            //审核不通过
            achievements.setIsApproved(0);
            List<String> errors = (List<String>) objectMap.get("error");
            String errorStr = "";
            for (String item : errors) {
                errorStr += item;
            }
            achievements.setVerifyContent(errorStr);
        } else {
            //审核中
            achievements.setIsApproved(2);
        }
        if (objectMap.containsKey("attribute")) {
            environmentAttributes = (List<EnvironmentAttribute>) objectMap.get("attribute");
        }
//        if (environmentAttributes == null || environmentAttributes.size() == 0) {
//            //审核不通过
//            achievements.setIsApproved(0);
//        } else {
//            //审核中
//            achievements.setIsApproved(2);
//        }
        //将更新前的文件置为历史数据
        achievementsFileRepository.updateFileIsHistory(achievements.getId(), achievements.getTypeId(), 1);
        Achievements achievements1 = achievementsRepository.save(achievements);
        //更新后删除属性信息，然后更新最新的属性信息
        if (achievements1 != null) {
            environmentAttributeService.deleteByAchievementId(achievements1.getId());
            if (environmentAttributes != null || environmentAttributes.size() > 0) {
                for (EnvironmentAttribute item : environmentAttributes) {
                    item.setAchievementId(achievements1.getId());
                }
                environmentAttributeService.saveAll(environmentAttributes);
            }
        }
        return achievements1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), achievements1) :
                new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState update(Integer isLayerFeature, Achievements achievements, MultipartFile multipartTextFile, List<MultipartFile> multipartVectorFiles, List<MultipartFile> multipartEvidenceFiles, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Optional<Claims> optional = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
        if (optional.isPresent()) {
            Claims claims = optional.get();
            String userName = claims.get("username").toString();
            String unitName = claims.get("unitName").toString();
            Object obj = claims.get("unit");
            Unit unit = com.alibaba.fastjson.JSONArray.parseObject(JSON.toJSONString(obj), Unit.class);
            if (unit != null) {
                achievements.setUnitId(unit.getCityId());
            }
            achievements.setReportUser(userName);
            achievements.setReportUnit(unitName);
        }
        Map<String, Object> objectMap = new HashMap<>();
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> textResultMap = new HashMap<>();
        Map<String, Object> vectorResultMap = new HashMap<>();
        List<Map<String, Object>> vectorMapList = new ArrayList<>();
        List<Map<String, Object>> textMapList = new ArrayList<>();
        List<String> vectorResultList = new ArrayList<>();
        List<String> textResultList = new ArrayList<>();
        List<String> vectorSuccessResultList = new ArrayList<>();
        List<String> textSuccessResultList = new ArrayList<>();
        List<EnvironmentAttribute> environmentAttributes = new ArrayList<>();
        List<AchievementsFile> achievementsFileList = new ArrayList<>();
        List<TextAchievements> textAchievementsList = new ArrayList<>();
        List<AchievementsType> achievementsTypes = achievementsTypeRepository.findAll();
        AchievementsType achievementsVectorType = achievementsTypes.stream().filter(s -> s.getCode().equals("VECTOR")).findFirst().get();
        AchievementsType achievementsTextType = achievementsTypes.stream().filter(s -> s.getCode().equals("TEXT")).findFirst().get();
        AchievementsType achievementsEvidenceType = achievementsTypes.stream().filter(s -> s.getCode().equals("EVIDENCE")).findFirst().get();
        List<VectorFileCategory> vectorFileCategoryList = vectorFileCategoryService.findAll();
        if (multipartVectorFiles != null && multipartEvidenceFiles != null) {
            vectorResultMap.put("false", vectorResultList);
            textResultMap.put("false", textResultList);
            vectorResultMap.put("true", vectorSuccessResultList);
            textResultMap.put("true", textSuccessResultList);
            vectorMapList.add(vectorResultMap);
            textMapList.add(textResultMap);
            String fileVectorPath = Constants.ACHIEVEMENTS_VECTOR_FILE;
            String fileTextPath = Constants.ACHIEVEMENTS_TEXT_FILE;
            String fileEvidencePath = Constants.ACHIEVEMENTS_EVIDENCE_FILE;
            //保存管控单元清单文本文件
            if (multipartTextFile != null && isLayerFeature == 0) {
                textAchievementsList = analysisTextFile(fileTextPath, achievementsFileList, multipartTextFile, achievements, achievementsTextType, request);
                if (textAchievementsList != null && textAchievementsList.size() > 0) {

                } else {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                }
            }
            //保存矢量文件
            if (multipartVectorFiles != null) {
                achievements.setTypeId(achievementsVectorType.getId());
                String fileServerPath = "";
                String uuid = UUID.randomUUID().toString();
                List<AchievementsFile> achievementsFiles = new ArrayList<>();
                for (int i = 0; i < multipartVectorFiles.size(); i++) {
                    AchievementsFile achievementsFile = new AchievementsFile();
                    String fjName = uuid + "_" + multipartVectorFiles.get(i).getOriginalFilename();
                    String fileOriginalFileName = multipartVectorFiles.get(i).getOriginalFilename();
                    String pathname = request.getSession(true).getServletContext().getRealPath("//") + fileVectorPath + fjName;
                    String filePathFinal = fileVectorPath + fjName;
                    System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                    if (FileUtil.fileUpload(multipartVectorFiles.get(i), pathname)) {
                        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
                    }
                    String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
                    if (!StringUtils.isEmpty(suffix)) {
                        if (suffix.equals("shp")) {
                            //当为shp文件时，对其进行解析
                            fileServerPath = pathname;
                        }
                        if (suffix.equals("prj")) {
                            BufferedReader bufferedReader = new BufferedReader(new FileReader(pathname));
                            String line = null;
                            String fileContent = "";
                            while ((line = bufferedReader.readLine()) != null) {
                                fileContent = line;
                            }
                            if (fileContent.contains("Coordinate System 2000")) {
                                vectorSuccessResultList.add("坐标系无误。");
                            } else {
                                vectorResultList.add("坐标系错误。");
                            }
                        }
                        achievementsFile.setFileType(suffix);
                    }
                    achievementsFile.setFilePath(filePathFinal);
                    achievementsFile.setFileName(fileOriginalFileName);
                    achievementsFile.setAchievementsTypeId(achievementsVectorType.getId());
                    achievementsFile.setIsHistory(0);
//                    achievementsFileList.add(achievementsFile);
                    achievementsFiles.add(achievementsFile);
                    achievementsFile.setContent(achievements.getContent());
                }
                if (achievementsFiles.size() <= 0) {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                }
                objectMap = analysisVector1(fileServerPath, achievements);
                achievementsFileList.addAll(achievementsFiles);
                achievements.setFiles(achievementsFileList);
                for (AchievementsFile file : achievementsFileList) {
                    file.setAchievements(achievements);
                }
            } else {
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), "审核不通过，缺少矢量文件");
            }
            //佐证材料
            if (multipartEvidenceFiles != null) {
                String fileServerPath = "";
                List<AchievementsFile> achievementsFiles = new ArrayList<>();
                for (int i = 0; i < multipartEvidenceFiles.size(); i++) {
                    String uuid = UUID.randomUUID().toString();
                    AchievementsFile achievementsFile = new AchievementsFile();
                    String fjName = uuid + "_" + multipartEvidenceFiles.get(i).getOriginalFilename();
                    String fileOriginalFileName = multipartEvidenceFiles.get(i).getOriginalFilename();
                    String pathname = request.getSession(true).getServletContext().getRealPath("//") + fileEvidencePath + fjName;
                    String filePathFinal = fileEvidencePath + fjName;
                    System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                    if (FileUtil.fileUpload(multipartEvidenceFiles.get(i), pathname)) {
                        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                    }
                    String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
                    if (!StringUtils.isEmpty(suffix)) {
                        achievementsFile.setFileType(suffix);
                    }
                    achievementsFile.setFilePath(filePathFinal);
                    achievementsFile.setFileName(fileOriginalFileName);
                    achievementsFile.setAchievementsTypeId(achievementsEvidenceType.getId());
                    achievementsFile.setIsHistory(0);
                    achievementsFileList.add(achievementsFile);
                    achievementsFiles.add(achievementsFile);
                    achievementsFile.setContent(achievements.getContent());
                }
                if (achievementsFiles.size() <= 0) {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                }
                for (AchievementsFile file : achievementsFiles) {
                    file.setAchievements(achievements);
                }
                textSuccessResultList.add("具备佐证材料。");
            } else {
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), "审核不通过，缺少佐证材料文件");
            }
            if (objectMap.containsKey("error")) {
                //审核不通过
                achievements.setIsApproved(0);
                List<String> errors = (List<String>) objectMap.get("error");
                String errorStr = "矢量文件解析出错：";
                for (String item : errors) {
                    errorStr += item + "/r/n";
                }
                achievements.setVerifyContent(errorStr);
                vectorResultList.add("矢量文件解析错误：" + errorStr);
            } else {
                vectorSuccessResultList.add("矢量文件解析成功。");
            }
            if (objectMap.containsKey("attribute")) {
                //校验管控清单和矢量文件属性是否一一对应
                environmentAttributes = (List<EnvironmentAttribute>) objectMap.get("attribute");
                if (textAchievementsList.size() > 0) {
                    String hjgkdybm = "";
                    boolean isExist = false;
                    for (EnvironmentAttribute item : environmentAttributes) {
                        boolean result = textAchievementsList.stream().anyMatch(s -> s.getUnitCode().trim().equals(item.getHJDYBM()));
                        if (!result) {
                            isExist = true;
                            hjgkdybm += item.getHJDYBM() + "/";
                        }
                    }
                    if (isExist) {
                        textResultList.add("环境管控清单中的数据和矢量数据中的属性不是一一对应。编码：" + hjgkdybm);
                    } else {
                        textSuccessResultList.add("具备管控清单文件。");
                        textSuccessResultList.add("环境管控清单和矢量数据相匹配。");
                    }
                }
            }
            resultMap.put("TEXT", textMapList);
            resultMap.put("VECTOR", vectorMapList);
            if (textResultList.size() > 0 || vectorResultList.size() > 0) {
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
            }
            //审核中
            achievements.setIsApproved(2);
            achievements.setVerifyContent("系统审核通过");
            //矢量属性解析后数据
            if (objectMap.containsKey("attribute")) {
                environmentAttributes = (List<EnvironmentAttribute>) objectMap.get("attribute");
            }
            //保存文本清单数据
            if (textAchievementsList != null) {
                textAchievementsService.saveAll(textAchievementsList);
            }
            achievements.setUploadDate(new Date());
            achievements.setVerifyType(0);

            //将更新前的文件置为历史数据
            achievementsFileRepository.updateFileIsHistory(achievements.getId(), 1);
            if (isLayerFeature == 0) {
                Catalog catalog = catalogService.findByCode("4");
                achievements.setCatalogId(catalog.getId());
            }
            Achievements achievements1 = achievementsRepository.save(achievements);
            //更新后删除属性信息，然后更新最新的属性信息
            if (achievements1 != null) {
                environmentAttributeService.deleteByAchievementId(achievements1.getId());
                if (environmentAttributes != null || environmentAttributes.size() > 0) {
                    for (EnvironmentAttribute item : environmentAttributes) {
                        item.setAchievementId(achievements1.getId());
                    }
                    environmentAttributeService.saveAll(environmentAttributes);
                }
            }
            return achievements1 != null ? new ResultState(StateInfo.SAVE_VERIFY_OK.getCode(), StateInfo.SAVE_VERIFY_OK.getMsg(), resultMap) :
                    new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), "保存成果失败");
        } else {
            //审核不通过
            return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
        }
    }

    @Override
    public ResultState delete(Long id, Long typeId) {
        List<AchievementsType> achievementsTypes = achievementsTypeRepository.findAll();
        Optional<Achievements> optional = achievementsRepository.findById(id);
        if (optional.isPresent()) {
            List<AchievementsFile> achievementsFileList = achievementsFileRepository.findByAchievementsIdAndIsHistory(id, 0);
            if (achievementsFileList != null && achievementsFileList.size() > 0) {
                //存在成果文件，则根据类型删除对应成果文件
                Optional<AchievementsType> optional1 = achievementsTypes.stream().filter(s -> s.getId() == typeId).findFirst();
                if (optional1.isPresent()) {
                    Optional<AchievementsType> vectorOptional = achievementsTypes.stream().filter(s -> s.getCode().equals("VECTOR")).findFirst();
                    Optional<AchievementsType> textOptional = achievementsTypes.stream().filter(s -> s.getCode().equals("TEXT")).findFirst();
                    //若为矢量或者文本成果，则两者强关联，同时删除
                    if (optional1.get().getCode().equals("VECTOR") || optional1.get().getCode().equals("TEXT")) {
                        achievementsFileRepository.deleteByAchievementsIdAndTextTypeIdOrVectorTypeId(id, vectorOptional.get().getId(), textOptional.get().getId());
                    } else {
                        achievementsFileRepository.deleteByAchievementsIdAndTypeId(id, optional1.get().getId());
                    }
                    //再次验证是否还包含成果文件数据
                    List<AchievementsFile> achievementsFileList1 = achievementsFileRepository.findByAchievementsIdAndIsHistory(id, 0);
                    if (achievementsFileList1 == null || achievementsFileList1.size() <= 0) {
                        //未存在成果文件，则直接进行删除
                        int result = achievementsRepository.delete(optional.get().getId());
                        return result > 0 ? new ResultState(StateInfo.DELETE_OK.getCode(), StateInfo.DELETE_OK.getMsg()) :
                                new ResultState(StateInfo.DELETE_ERROR_2.getCode(), StateInfo.DELETE_ERROR_2.getMsg());
                    }
                }
            } else {
                //未存在成果文件，则直接进行删除
                int result = achievementsRepository.delete(optional.get().getId());
                return result > 0 ? new ResultState(StateInfo.DELETE_OK.getCode(), StateInfo.DELETE_OK.getMsg()) :
                        new ResultState(StateInfo.DELETE_ERROR_2.getCode(), StateInfo.DELETE_ERROR_2.getMsg());
            }
        }
        return new ResultState(StateInfo.DELETE_ERROR_2.getCode(), StateInfo.DELETE_ERROR_2.getMsg());
    }

    @Override
    public ResultState manualVerify(Integer isApproved, String verifyContent, Long achievementId, HttpServletRequest request) throws Exception {
        Optional<Achievements> optional1 = achievementsRepository.findById(achievementId);
        if (optional1.isPresent()) {
            String token = request.getHeader("token");
            Optional<Claims> optional = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
            if (optional.isPresent()) {
                Claims claims = optional.get();
                String userName = claims.get("username").toString();
                String unitName = claims.get("unitName").toString();
                achievementsRepository.updateVerifyUser(userName, unitName, achievementId);
            }
            if (isApproved.equals(1)) {
                verifyContent = "人工审核通过：" + verifyContent;
            } else {
                verifyContent = "人工审核不通过：" + verifyContent;
            }
            int result = achievementsRepository.manualVerify(isApproved, verifyContent, achievementId, new Date());
            return result > 0 ? new ResultState(StateInfo.SAVE_VERIFY_OK.getCode(), StateInfo.SAVE_VERIFY_OK.getMsg(), result) :
                    new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg());
        }
        return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg());
    }

    @Override
    public ResultState vectorConvert(List<MultipartFile> fileList, HttpServletRequest request) throws Exception {
        if(CollectionUtils.isNotEmpty(fileList)){
            String fileShpPath = "";
            String fileShpName = "";
            for (MultipartFile multipartFile : fileList) {
                String uuid = UUID.randomUUID().toString();
                String fjName = uuid + "_" + multipartFile.getOriginalFilename();
                String vectorFilePath = request.getSession(true).getServletContext().getRealPath("//") + "res/achievements/convert/vector/" + fjName;
                if(fjName.substring(fjName.lastIndexOf(".") + 1).equals("shp")){
                    fileShpPath = vectorFilePath;
                    fileShpName = fjName;
                }
                if (FileUtil.fileUpload(multipartFile, vectorFilePath)) {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
                }
            }
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(fileShpName)){
                String topologyUDBXFile = "/res/achievements/topologyUDBX.udbx";
                String serverPath = this.getClass().getResource(topologyUDBXFile).getPath();
                serverPath = serverPath.substring(serverPath.indexOf("/") + 1, serverPath.length());
                convert(serverPath,fileShpPath,fileShpName);
            }


        }
        return null;
    }

    /**
     * 解析矢量文件数据
     *
     * @param filePath
     * @param achievements
     * @return
     */
    private List<EnvironmentAttribute> analysisVector(String filePath, Achievements achievements) {
        List<EnvironmentAttribute> environmentAttributeList = new ArrayList<>();
        //矢量数据时，解析矢量文件
        String jsonString = "";
        String HJDYBM = "";
        if (!StringUtils.isEmpty(filePath)) {
            JSONArray shpFileAttributes = GeoUtils.getShpFileAttributes(filePath);
            if (shpFileAttributes.size() > 0) {
                for (int i = 0; i < shpFileAttributes.size(); i++) {
                    JSONObject object = (JSONObject) shpFileAttributes.get(i);
                    if (object.containsKey(Constants.HJYSGKFQBM) || object.containsKey(Constants.HJGKDYBM)) {
                        EnvironmentAttribute environmentAttribute = new EnvironmentAttribute();
                        if (object.containsKey(Constants.HJYSGKFQBM)) {
                            HJDYBM = object.get(Constants.HJYSGKFQBM).toString();
                            if (!StringUtils.isEmpty(HJDYBM)) {
                                environmentAttribute.setHJDYBM(HJDYBM);
                                String HJYSGKFQMC = object.get(Constants.HJYSGKFQMC).toString();
                                String catalogCode = HJDYBM.substring(8, 11);//截取对应目录代码
                                if (StringUtils.isEmpty(HJYSGKFQMC) || StringUtils.isEmpty(catalogCode)) {
                                    return null;
                                }
                                environmentAttribute.setHJDYMC(HJYSGKFQMC);
                                if (!StringUtils.isEmpty(catalogCode)) {
                                    Catalog catalog = catalogService.findLikeKeyCode(catalogCode);
                                    if (catalog != null) {
                                        achievements.setCatalogId(catalog.getId());
                                        environmentAttribute.setCatalogId(catalog.getId());
                                    } else {
                                        return null;
                                    }
                                }
                                String hjysdm = HJDYBM.substring(9, 10);//截取环境要素代码
                                switch (hjysdm) {
                                    case "1"://生态
                                    case "3"://大气
                                    case "4"://土壤
                                    case "5"://自然资源
                                        String GKQFL = object.get("GKQFL").toString();
                                        String HJYS = object.get("HJYS").toString();
                                        if (StringUtils.isEmpty(GKQFL) || StringUtils.isEmpty(HJYS)) {
                                            return null;
                                        }
                                        environmentAttribute.setGKQFL(GKQFL);
                                        environmentAttribute.setHJYS(HJYS);
                                        environmentAttribute.setTypeId(Long.valueOf(2));
                                        break;
                                    case "2"://水
                                        String LYMC = object.get("LYMC").toString();
                                        String HDMC = object.get("HDMC").toString();
                                        String KZDMQDJD = object.get("KZDMQDJD").toString();
                                        String KZDMQDWD = object.get("KZDMQDWD").toString();
                                        String KZDMZDJD = object.get("KZDMZDJD").toString();
                                        String KZDMZDWD = object.get("KZDMZDWD").toString();
                                        if (StringUtils.isEmpty(LYMC) || StringUtils.isEmpty(HDMC) || StringUtils.isEmpty(KZDMQDJD) || StringUtils.isEmpty(KZDMQDWD) || StringUtils.isEmpty(KZDMZDJD) || StringUtils.isEmpty(KZDMZDWD)) {
                                            return null;
                                        }
                                        environmentAttribute.setLYMC(LYMC);
                                        environmentAttribute.setHDMC(HDMC);
                                        environmentAttribute.setKZDMQDJD(KZDMQDJD);
                                        environmentAttribute.setKZDMQDWD(KZDMQDWD);
                                        environmentAttribute.setKZDMZDJD(KZDMZDJD);
                                        environmentAttribute.setKZDMZDWD(KZDMZDWD);
                                        environmentAttribute.setTypeId(Long.valueOf(3));
                                        break;
                                }
                                String PROV = object.get("PROV").toString();
                                String CITY = object.get("CITY").toString();
                                String COUNTY = object.get("COUNTY").toString();
                                String YSXL = object.get("YSXL").toString();
                                if (StringUtils.isEmpty(PROV) || StringUtils.isEmpty(CITY) || StringUtils.isEmpty(COUNTY) || StringUtils.isEmpty(YSXL)) {
                                    return null;
                                }
                                environmentAttribute.setPROV(PROV);
                                environmentAttribute.setCITY(CITY);
                                environmentAttribute.setCOUNTY(COUNTY);
                                environmentAttribute.setYSXL(YSXL);
                                environmentAttribute.setShapeArea(object.get("SHAPE_Area") == null ? object.get("Shape_Area").toString() : object.get("SHAPE_Area").toString());
                                environmentAttribute.setShapeLeng(object.get("SHAPE_Leng") == null ? object.get("Shape_Leng").toString() : object.get("SHAPE_Leng").toString());
                            } else {
                                return null;
                            }
                        }
                        if (object.containsKey(Constants.HJGKDYBM)) {
                            HJDYBM = object.get(Constants.HJGKDYBM).toString();
                            if (!StringUtils.isEmpty(HJDYBM)) {
                                environmentAttribute.setHJDYBM(HJDYBM);
                                String HJGKDYMC = object.get(Constants.HJGKDYMC).toString();
                                String catalogCode = HJDYBM.substring(8, 9);//截取对应目录代码
                                if (StringUtils.isEmpty(HJGKDYMC) || StringUtils.isEmpty(catalogCode)) {
                                    return null;
                                }
                                environmentAttribute.setHJDYMC(HJGKDYMC);
                                if (!StringUtils.isEmpty(catalogCode)) {
                                    Catalog catalog = catalogService.findByKeyCode(catalogCode);
                                    if (catalog != null) {
                                        achievements.setCatalogId(catalog.getId());
                                        environmentAttribute.setCatalogId(catalog.getId());
                                    } else {
                                        return null;
                                    }
                                }
                                String REMARKS = object.get("REMARKS").toString();
                                String PROV = object.get("PROV").toString();
                                String CITY = object.get("CITY").toString();
                                String COUNTY = object.get("COUNTY").toString();
                                String GKDYFL = object.get("GKDYFL").toString();
                                if (StringUtils.isEmpty(PROV) || StringUtils.isEmpty(CITY) || StringUtils.isEmpty(COUNTY) || StringUtils.isEmpty(GKDYFL)) {
                                    return null;
                                }
                                environmentAttribute.setTypeId(Long.valueOf(1));
                                environmentAttribute.setRemarks(REMARKS);
                                environmentAttribute.setPROV(PROV);
                                environmentAttribute.setCITY(CITY);
                                environmentAttribute.setCOUNTY(COUNTY);
                                environmentAttribute.setGKDYFL(GKDYFL);
                                environmentAttribute.setShapeArea(object.get("SHAPE_Area") == null ? object.get("Shape_Area").toString() : object.get("SHAPE_Area").toString());
                                environmentAttribute.setShapeLeng(object.get("SHAPE_Leng") == null ? object.get("Shape_Leng").toString() : object.get("SHAPE_Leng").toString());
                            } else {
                                return null;
                            }
                        }
                        environmentAttributeList.add(environmentAttribute);
                    } else {
                        return null;
                    }
                }
            }
        }
        return environmentAttributeList;
    }

    /**
     * 解析矢量文件数据
     *
     * @param filePath
     * @param achievements
     * @return
     */
    private Map<String, Object> analysisVector1(String filePath, Achievements achievements) {
        Map<String, Object> resultMap = new HashMap<>();
        List<String> errors = new ArrayList<>();

        Map<String, Object> attributeMap = new HashMap<>();
        List<String> attributeCompleteErrors = new ArrayList<>();//属性项是否完整
        attributeMap.put("attributeComplete", attributeCompleteErrors);
        List<String> attributeLengthErrors = new ArrayList<>();//类型长度是否正确
        attributeMap.put("attributeLength", attributeLengthErrors);
        List<String> attributeContentErrors = new ArrayList<>();//内容值是否正确
        attributeMap.put("attributeContent", attributeContentErrors);
        List<String> attributeCodeErrors = new ArrayList<>();//编码是否规范
        attributeMap.put("attributeCode", attributeCodeErrors);

        List<EnvironmentAttribute> environmentAttributeList = new ArrayList<>();
        //矢量数据时，解析矢量文件
        String jsonString = "";
        String HJDYBM = "";
        if (!StringUtils.isEmpty(filePath)) {
            JSONArray shpFileAttributes = GeoUtils.getShpFileAttributes(filePath);
            if (shpFileAttributes.size() > 0) {
                int flagInt = 0;
                int flagInt1 = 0;
                for (int i = 0; i < shpFileAttributes.size(); i++) {
                    JSONObject object = (JSONObject) shpFileAttributes.get(i);
                    if (object.containsKey(Constants.HJYSGKFQBM) || object.containsKey(Constants.HJGKDYBM)) {
                        EnvironmentAttribute environmentAttribute = new EnvironmentAttribute();
                        if (object.containsKey(Constants.HJYSGKFQBM)) {
                            HJDYBM = object.get(Constants.HJYSGKFQBM).toString();
                            if (HJDYBM.length() != 15) {
                                errors.add(HJDYBM + ":" + "环境要素管控分区编码长度不正确。");
                                attributeLengthErrors.add(HJDYBM + ":" + "环境要素管控分区编码长度不正确。");
                            }
                            if (!StringUtils.isEmpty(HJDYBM)) {
                                environmentAttribute.setHJDYBM(HJDYBM);
                                String HJYSGKFQMC = object.get(Constants.HJYSGKFQMC).toString();
                                String catalogCode = HJDYBM.substring(8, 11);//截取对应目录代码
                                if (StringUtils.isEmpty(HJYSGKFQMC) || StringUtils.isEmpty(catalogCode)) {
                                    errors.add(HJDYBM + ":" + "环境要素管控分区名称或编码中对应目录编码不正确。");
                                    attributeContentErrors.add(HJDYBM + ":" + "环境要素管控分区名称或编码中对应目录编码不正确。");
                                    attributeCodeErrors.add(HJDYBM);
                                }
                                environmentAttribute.setHJDYMC(HJYSGKFQMC);
                                if (!StringUtils.isEmpty(catalogCode)) {
                                    Catalog catalog = null;
                                    if (catalogCode.equals("1") || catalogCode.equals("2") || catalogCode.equals("3")) {
                                        catalog = catalogService.findByCode("4");
                                    } else {
                                        catalog = catalogService.findLikeKeyCode(catalogCode);
                                    }
                                    if (catalog != null) {
                                        achievements.setCatalogId(catalog.getId());
                                        environmentAttribute.setCatalogId(catalog.getId());
                                    } else {
                                        errors.add(HJDYBM + ":" + "环境要素管控分区编码中对应目录编码不正确。");
                                        attributeCodeErrors.add(HJDYBM);
                                    }
                                }
                                String hjysdm = HJDYBM.substring(9, 10);//截取环境要素代码
                                switch (hjysdm) {
                                    case "1"://生态
                                    case "3"://大气
                                    case "4"://土壤
                                    case "5"://自然资源
                                        String GKQFL = object.get("GKQFL").toString();
                                        String HJYS = object.get("HJYS").toString();
                                        if (StringUtils.isEmpty(GKQFL) || StringUtils.isEmpty(HJYS)) {
                                            errors.add(HJDYBM + ":" + "环境要素管控分区编码中管控区分类或环境要素编码不正确。");
                                            attributeContentErrors.add(HJDYBM + ":" + "环境要素管控分区编码中管控区分类或环境要素编码不正确。");
                                        }
                                        environmentAttribute.setGKQFL(GKQFL);
                                        environmentAttribute.setHJYS(HJYS);
                                        environmentAttribute.setTypeId(Long.valueOf(2));
                                        break;
                                    case "2"://水
                                        String LYMC = object.get("LYMC").toString();
                                        String HDMC = object.get("HDMC").toString();
                                        String KZDMQDJD = object.get("KZDMQDJD").toString();
                                        String KZDMQDWD = object.get("KZDMQDWD").toString();
                                        String KZDMZDJD = object.get("KZDMZDJD").toString();
                                        String KZDMZDWD = object.get("KZDMZDWD").toString();
                                        if (StringUtils.isEmpty(LYMC) || StringUtils.isEmpty(HDMC) || StringUtils.isEmpty(KZDMQDJD) || StringUtils.isEmpty(KZDMQDWD) || StringUtils.isEmpty(KZDMZDJD) || StringUtils.isEmpty(KZDMZDWD)) {
                                            errors.add(HJDYBM + ":" + "环境要素管控分区编码中流域名称或河段名称或控制断面起点经度或控制断面起点维度或控制断面终点经度或控制断面终点维度数据不完整。");
                                            attributeContentErrors.add(HJDYBM + ":" + "环境要素管控分区编码中流域名称或河段名称或控制断面起点经度或控制断面起点维度或控制断面终点经度或控制断面终点维度数据不完整。");
                                        }
                                        environmentAttribute.setLYMC(LYMC);
                                        environmentAttribute.setHDMC(HDMC);
                                        environmentAttribute.setKZDMQDJD(KZDMQDJD);
                                        environmentAttribute.setKZDMQDWD(KZDMQDWD);
                                        environmentAttribute.setKZDMZDJD(KZDMZDJD);
                                        environmentAttribute.setKZDMZDWD(KZDMZDWD);
                                        environmentAttribute.setTypeId(Long.valueOf(3));
                                        break;
                                    default:
                                        errors.add(HJDYBM + ":" + "环境要素管控分区要素编码不正确。");
                                        attributeContentErrors.add(HJDYBM + ":" + "环境要素管控分区要素编码不正确。");
                                        attributeCodeErrors.add(HJDYBM);
                                        break;
                                }
                                String PROV = object.get("PROV").toString();
                                String CITY = object.get("CITY").toString();
                                String COUNTY = object.get("COUNTY").toString();
                                String YSXL = object.get("YSXL").toString();
                                if (StringUtils.isEmpty(PROV) || StringUtils.isEmpty(CITY) || StringUtils.isEmpty(COUNTY)) {
                                    errors.add(HJDYBM + ":" + "环境要素管控分区行政区划编码不完整。");
                                    attributeContentErrors.add(HJDYBM + ":" + "环境要素管控分区行政区划编码不完整。");
                                }
                                if (StringUtils.isEmpty(YSXL)) {
                                    errors.add(HJDYBM + ":" + "环境要素管控分区要素细类编码不正确。");
                                    attributeContentErrors.add(HJDYBM + ":" + "环境要素管控分区要素细类编码不正确。");
                                    attributeCodeErrors.add(HJDYBM);
                                }
                                environmentAttribute.setPROV(PROV);
                                environmentAttribute.setCITY(CITY);
                                environmentAttribute.setCOUNTY(COUNTY);
                                environmentAttribute.setYSXL(YSXL);
                                environmentAttribute.setShapeArea(object.get("SHAPE_Area") == null ? object.get("Shape_Area").toString() : object.get("SHAPE_Area").toString());
                                environmentAttribute.setShapeLeng(object.get("SHAPE_Leng") == null ? object.get("Shape_Leng").toString() : object.get("SHAPE_Leng").toString());
                            } else {
                                flagInt++;
                                if (flagInt <= 1) {
                                    errors.add("环境管控编码为空。");
                                    attributeCompleteErrors.add("环境管控编码为空。");
                                }
                            }
                        }
                        if (object.containsKey(Constants.HJGKDYBM)) {
                            HJDYBM = object.get(Constants.HJGKDYBM).toString();
                            if (HJDYBM.length() != 13) {
                                errors.add(HJDYBM + ":" + "环境管控单元编码编码长度不正确。");
                                attributeLengthErrors.add(HJDYBM + ":" + "环境管控单元编码编码长度不正确。");
                            }
                            if (!StringUtils.isEmpty(HJDYBM)) {
                                environmentAttribute.setHJDYBM(HJDYBM);
                                String HJGKDYMC = object.get(Constants.HJGKDYMC).toString();
                                String catalogCode = HJDYBM.substring(8, 9);//截取对应目录代码
                                if (StringUtils.isEmpty(HJGKDYMC) || StringUtils.isEmpty(catalogCode)) {
                                    errors.add(HJDYBM + ":" + "环境管控单元名称或编码中对应目录编码不正确。");
                                    attributeContentErrors.add(HJDYBM + ":" + "环境管控单元名称或编码中对应目录编码不正确。");
                                    attributeCodeErrors.add(HJDYBM);
                                }
                                environmentAttribute.setHJDYMC(HJGKDYMC);
                                if (!StringUtils.isEmpty(catalogCode)) {
                                    Catalog catalog = null;
                                    Catalog catalog1 = catalogService.findByKeyCode(catalogCode);
                                    if (catalogCode.equals("1") || catalogCode.equals("2") || catalogCode.equals("3")) {
                                        catalog = catalogService.findByCode("4");
                                    } else {
                                        catalog = catalogService.findByKeyCode(catalogCode);
                                    }
                                    if (catalog1 != null) {
                                        environmentAttribute.setCatalogId(catalog1.getId());
                                    } else {
                                        errors.add(HJDYBM + ":" + "环境管控单元编码中对应目录编码不正确。");
                                        attributeCodeErrors.add(HJDYBM);
                                    }
                                    if (catalog != null) {
                                        achievements.setCatalogId(catalog.getId());
                                    }
                                }
                                String REMARKS = object.get("REMARKS").toString();
                                String PROV = object.get("PROV").toString();
                                String CITY = object.get("CITY").toString();
                                String COUNTY = object.get("COUNTY").toString();
                                String GKDYFL = object.get("GKDYFL").toString();
                                if (StringUtils.isEmpty(PROV) || StringUtils.isEmpty(CITY) || StringUtils.isEmpty(COUNTY)) {
                                    errors.add(HJDYBM + ":" + "环境要素管控分区行政区划编码不完整。");
                                    attributeContentErrors.add(HJDYBM + ":" + "环境要素管控分区行政区划编码不完整。");
                                }
                                if (StringUtils.isEmpty(GKDYFL)) {
                                    errors.add(HJDYBM + ":" + "环境要素管控分区管控单元分类编码不完整。");
                                    attributeContentErrors.add(HJDYBM + ":" + "环境要素管控分区管控单元分类编码不完整。");
                                }
                                environmentAttribute.setTypeId(Long.valueOf(1));
                                environmentAttribute.setRemarks(REMARKS);
                                environmentAttribute.setPROV(PROV);
                                environmentAttribute.setCITY(CITY);
                                environmentAttribute.setCOUNTY(COUNTY);
                                environmentAttribute.setGKDYFL(GKDYFL);
                                environmentAttribute.setShapeArea(object.get("SHAPE_Area") == null ? object.get("Shape_Area").toString() : object.get("SHAPE_Area").toString());
                                environmentAttribute.setShapeLeng(object.get("SHAPE_Leng") == null ? object.get("Shape_Leng").toString() : object.get("SHAPE_Leng").toString());
                            } else {
                                flagInt1++;
                                if (flagInt1 <= 1) {
                                    errors.add("环境管控单元编码编码为空。");
                                    attributeCompleteErrors.add("环境管控单元编码编码为空。");
                                }
                            }
                        }
                        environmentAttributeList.add(environmentAttribute);
                    } else {
                        errors.add("环境管控编码为空。");
                        attributeCompleteErrors.add("环境管控编码为空。");
                    }
                }
            }
        }
        if (errors.size() > 0) {
            resultMap.put("error", errors);
        }
        if (environmentAttributeList.size() > 0) {
            resultMap.put("attribute", environmentAttributeList);
        }
        resultMap.put("attributeResult", attributeMap);
        return resultMap;
    }

    /**
     * 解析矢量文件数据
     *
     * @param filePath
     * @param achievements
     * @return
     */
    private Map<String, Object> analysisVector1(String filePath, String fileName, Achievements achievements) {
        Map<String, Object> resultMap = new HashMap<>();
        List<String> errors = new ArrayList<>();

        Map<String, Object> attributeMap = new HashMap<>();
        List<String> attributeCompleteErrors = new ArrayList<>();//属性项是否完整
        attributeMap.put("attributeComplete", attributeCompleteErrors);
        List<String> attributeLengthErrors = new ArrayList<>();//类型长度是否正确
        attributeMap.put("attributeLength", attributeLengthErrors);
        List<String> attributeContentErrors = new ArrayList<>();//内容值是否正确
        attributeMap.put("attributeContent", attributeContentErrors);
        List<String> attributeCodeErrors = new ArrayList<>();//编码是否规范
        attributeMap.put("attributeCode", attributeCodeErrors);

        List<EnvironmentAttribute> environmentAttributeList = new ArrayList<>();
        List<EnvironmentAttribute> environmentAttributesDY = new ArrayList<>();//管控单元矢量解析数据
        List<EnvironmentAttribute> environmentAttributesYS = new ArrayList<>();//管控要素矢量解析数据
        //矢量数据时，解析矢量文件
        String jsonString = "";
        String HJDYBM = "";
        try {
            if (!StringUtils.isEmpty(filePath)) {
                JSONArray shpFileAttributes = GeoUtils.getShpFileAttributes(filePath);
                if (shpFileAttributes.size() > 0) {
                    int flagInt = 0;
                    int flagInt1 = 0;
                    for (int i = 0; i < shpFileAttributes.size(); i++) {
                        JSONObject object = (JSONObject) shpFileAttributes.get(i);
                        if (object.containsKey("the_geom") && !object.containsKey(Constants.HJYSGKFQBM) && !object.containsKey(Constants.HJGKDYBM)) {
                            continue;
                        }
                        if (object.containsKey(Constants.HJYSGKFQBM) || object.containsKey(Constants.HJGKDYBM)) {
                            EnvironmentAttribute environmentAttribute = new EnvironmentAttribute();
                            if (object.containsKey(Constants.HJYSGKFQBM)) {
                                HJDYBM = object.get(Constants.HJYSGKFQBM).toString();
                                if (HJDYBM.equals("YS6571021110001")) {
                                    System.out.println(fileName);
                                }
                                if (HJDYBM.length() != 15) {
                                    errors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区编码长度不正确。");
                                    attributeLengthErrors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区编码长度不正确。");
                                }
                                if (!StringUtils.isEmpty(HJDYBM)) {
                                    environmentAttribute.setHJDYBM(HJDYBM);
                                    String HJYSGKFQMC = object.get(Constants.HJYSGKFQMC).toString();
                                    String catalogCode = HJDYBM.substring(8, 11);//截取对应目录代码
                                    if (StringUtils.isEmpty(HJYSGKFQMC) || StringUtils.isEmpty(catalogCode)) {
                                        errors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区名称或编码中对应目录编码不正确。");
                                        attributeContentErrors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区名称或编码中对应目录编码不正确。");
                                        attributeCodeErrors.add(fileName + "--" + HJDYBM);
                                    }
                                    environmentAttribute.setHJDYMC(HJYSGKFQMC);
                                    if (!StringUtils.isEmpty(catalogCode)) {
                                        Catalog catalog = null;
                                        if (catalogCode.equals("1") || catalogCode.equals("2") || catalogCode.equals("3")) {
                                            catalog = catalogService.findByCode("4");
                                        } else {
                                            catalog = catalogService.findLikeKeyCode(catalogCode);
                                        }
                                        if (catalog != null) {
                                            achievements.setCatalogId(catalog.getId());
                                            environmentAttribute.setCatalogId(catalog.getId());
                                        } else {
                                            errors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区编码中对应目录编码不正确。");
                                            attributeCodeErrors.add(fileName + "--" + HJDYBM);
                                        }
                                    }
                                    String hjysdm = HJDYBM.substring(9, 10);//截取环境要素代码
                                    switch (hjysdm) {
                                        case "1"://生态
                                        case "3"://大气
                                        case "4"://土壤
                                        case "5"://自然资源
                                            String GKQFL = object.get("GKQFL").toString();
                                            String HJYS = object.get("HJYS").toString();
                                            if (StringUtils.isEmpty(GKQFL) || StringUtils.isEmpty(HJYS)) {
                                                errors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区编码中管控区分类或环境要素编码不正确。");
                                                attributeContentErrors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区编码中管控区分类或环境要素编码不正确。");
                                            }
                                            environmentAttribute.setGKQFL(GKQFL);
                                            environmentAttribute.setHJYS(HJYS);
                                            environmentAttribute.setTypeId(Long.valueOf(2));
                                            break;
                                        case "2"://水
                                            String LYMC = object.get("LYMC").toString();
                                            String HDMC = object.get("HDMC").toString();
                                            String KZDMQDJD = object.get("KZDMQDJD").toString();
                                            String KZDMQDWD = object.get("KZDMQDWD").toString();
                                            String KZDMZDJD = object.get("KZDMZDJD").toString();
                                            String KZDMZDWD = object.get("KZDMZDWD").toString();
                                            if (StringUtils.isEmpty(LYMC) || StringUtils.isEmpty(HDMC) || StringUtils.isEmpty(KZDMQDJD) || StringUtils.isEmpty(KZDMQDWD) || StringUtils.isEmpty(KZDMZDJD) || StringUtils.isEmpty(KZDMZDWD)) {
                                                errors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区编码中流域名称或河段名称或控制断面起点经度或控制断面起点维度或控制断面终点经度或控制断面终点维度数据不完整。");
                                                attributeContentErrors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区编码中流域名称或河段名称或控制断面起点经度或控制断面起点维度或控制断面终点经度或控制断面终点维度数据不完整。");
                                            }
                                            environmentAttribute.setLYMC(LYMC);
                                            environmentAttribute.setHDMC(HDMC);
                                            environmentAttribute.setKZDMQDJD(KZDMQDJD);
                                            environmentAttribute.setKZDMQDWD(KZDMQDWD);
                                            environmentAttribute.setKZDMZDJD(KZDMZDJD);
                                            environmentAttribute.setKZDMZDWD(KZDMZDWD);
                                            environmentAttribute.setTypeId(Long.valueOf(3));
                                            break;
                                        default:
                                            errors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区要素编码不正确。");
                                            attributeContentErrors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区要素编码不正确。");
                                            attributeCodeErrors.add(fileName + "--" + HJDYBM);
                                            break;
                                    }
                                    String PROV = object.get("PROV").toString();
                                    String CITY = object.get("CITY").toString();
                                    String COUNTY = object.get("COUNTY").toString();
                                    String YSXL = object.get("YSXL").toString();
                                    if (StringUtils.isEmpty(PROV) || StringUtils.isEmpty(CITY) || StringUtils.isEmpty(COUNTY)) {
                                        errors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区行政区划编码不完整。");
                                        attributeContentErrors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区行政区划编码不完整。");
                                    }
                                    if (StringUtils.isEmpty(YSXL)) {
                                        errors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区要素细类编码不正确。");
                                        attributeContentErrors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区要素细类编码不正确。");
                                        attributeCodeErrors.add(fileName + "--" + HJDYBM);
                                    }
                                    environmentAttribute.setPROV(PROV);
                                    environmentAttribute.setCITY(CITY);
                                    environmentAttribute.setCOUNTY(COUNTY);
                                    environmentAttribute.setYSXL(YSXL);
                                    environmentAttribute.setShapeArea(object.get("SHAPE_Area") == null ? object.get("Shape_Area").toString() : object.get("SHAPE_Area").toString());
                                    environmentAttribute.setShapeLeng(object.get("SHAPE_Leng") == null ? object.get("Shape_Leng").toString() : object.get("SHAPE_Leng").toString());
                                } else {
                                    flagInt++;
                                    if (flagInt <= 1) {
                                        errors.add(fileName + "--" + "环境管控编码为空。");
                                        attributeCompleteErrors.add(fileName + "--" + "环境管控编码为空。");
                                    }
                                }
                                environmentAttributesYS.add(environmentAttribute);
                            }

                            if (object.containsKey(Constants.HJGKDYBM)) {
                                HJDYBM = object.get(Constants.HJGKDYBM).toString();
                                if (HJDYBM.equals("YS6571021110001")) {
                                    System.out.println(fileName);
                                }
                                if (HJDYBM.length() != 13) {
                                    errors.add(fileName + "--" + HJDYBM + ":" + "环境管控单元编码编码长度不正确。");
                                    attributeLengthErrors.add(fileName + "--" + HJDYBM + ":" + "环境管控单元编码编码长度不正确。");
                                }
                                if (!StringUtils.isEmpty(HJDYBM)) {
                                    environmentAttribute.setHJDYBM(HJDYBM);
                                    String HJGKDYMC = object.get(Constants.HJGKDYMC).toString();
                                    String catalogCode = HJDYBM.substring(8, 9);//截取对应目录代码
                                    if (StringUtils.isEmpty(HJGKDYMC) || StringUtils.isEmpty(catalogCode)) {
                                        errors.add(fileName + "--" + HJDYBM + ":" + "环境管控单元名称或编码中对应目录编码不正确。");
                                        attributeContentErrors.add(fileName + "--" + HJDYBM + ":" + "环境管控单元名称或编码中对应目录编码不正确。");
                                        attributeCodeErrors.add(fileName + "--" + HJDYBM);
                                    }
                                    environmentAttribute.setHJDYMC(HJGKDYMC);
                                    if (!StringUtils.isEmpty(catalogCode)) {
                                        Catalog catalog = null;
                                        Catalog catalog1 = catalogService.findByKeyCode(catalogCode);
                                        if (catalogCode.equals("1") || catalogCode.equals("2") || catalogCode.equals("3")) {
                                            catalog = catalogService.findByCode("4");
                                        } else {
                                            catalog = catalogService.findByKeyCode(catalogCode);
                                        }
                                        if (catalog1 != null) {
                                            environmentAttribute.setCatalogId(catalog1.getId());
                                        } else {
                                            errors.add(fileName + "--" + HJDYBM + ":" + "环境管控单元编码中对应目录编码不正确。");
                                            attributeCodeErrors.add(fileName + "--" + HJDYBM);
                                        }
                                        if (catalog != null) {
                                            achievements.setCatalogId(catalog.getId());
                                        }
                                    }
                                    String REMARKS = object.get("REMARKS").toString();
                                    String PROV = object.get("PROV").toString();
                                    String CITY = object.get("CITY").toString();
                                    String COUNTY = object.get("COUNTY").toString();
                                    String GKDYFL = object.get("GKDYFL").toString();
                                    if (StringUtils.isEmpty(PROV) || StringUtils.isEmpty(CITY) || StringUtils.isEmpty(COUNTY)) {
                                        errors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区行政区划编码不完整。");
                                        attributeContentErrors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区行政区划编码不完整。");
                                    }
                                    if (StringUtils.isEmpty(GKDYFL)) {
                                        errors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区管控单元分类编码不完整。");
                                        attributeContentErrors.add(fileName + "--" + HJDYBM + ":" + "环境要素管控分区管控单元分类编码不完整。");
                                    }
                                    environmentAttribute.setTypeId(Long.valueOf(1));
                                    environmentAttribute.setRemarks(REMARKS);
                                    environmentAttribute.setPROV(PROV);
                                    environmentAttribute.setCITY(CITY);
                                    environmentAttribute.setCOUNTY(COUNTY);
                                    environmentAttribute.setGKDYFL(GKDYFL);
                                    environmentAttribute.setShapeArea(object.get("SHAPE_Area") == null ? object.get("Shape_Area").toString() : object.get("SHAPE_Area").toString());
                                    environmentAttribute.setShapeLeng(object.get("SHAPE_Leng") == null ? object.get("Shape_Leng").toString() : object.get("SHAPE_Leng").toString());
                                } else {
                                    flagInt1++;
                                    if (flagInt1 <= 1) {
                                        errors.add(fileName + "--" + "环境管控单元编码编码为空。");
                                        attributeCompleteErrors.add(fileName + "--" + "环境管控单元编码编码为空。");
                                    }
                                }
                                environmentAttributesDY.add(environmentAttribute);
                            }
                            environmentAttributeList.add(environmentAttribute);
                        } else {
                            errors.add(fileName + "--" + "环境管控编码为空。");
                            attributeCompleteErrors.add(fileName + "--" + "环境管控编码为空。");
                        }
                    }
                }
            }
            if (errors.size() > 0) {
                resultMap.put("error", errors);
            }
            if (environmentAttributeList.size() > 0) {
                resultMap.put("attribute", environmentAttributeList);
            }
            if (!environmentAttributesYS.isEmpty()) {
                resultMap.put("attributeYS", environmentAttributesYS);
            }
            if (!environmentAttributesDY.isEmpty()) {
                resultMap.put("attributeDY", environmentAttributesDY);
            }
            resultMap.put("attributeResult", attributeMap);
        }catch (Exception e){
            errors.add("矢量数据问题，解析报错。");
            resultMap.put("error", errors);
        }
        return resultMap;
    }

    /**
     * 解析文本文件
     *
     * @param filePath
     * @param achievementsFiles
     * @param multipartFile
     */
    private List<TextAchievements> analysisTextFile(String filePath, List<AchievementsFile> achievementsFiles, MultipartFile multipartFile, Achievements achievements, AchievementsType achievementsType, HttpServletRequest request) throws IOException {
        List<TextAchievements> textAchievementsList = new ArrayList<>();
        String fileServerPath = "";
        String uuid = UUID.randomUUID().toString();
        AchievementsFile achievementsFile = new AchievementsFile();
        String fjName = uuid + "_" + multipartFile.getOriginalFilename();
        String fileOriginalFileName = multipartFile.getOriginalFilename();
        String pathname = request.getSession(true).getServletContext().getRealPath("//") + filePath + fjName;
        String filePathFinal = filePath + fjName;
        System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
        if (!FileUtil.fileUpload(multipartFile, pathname)) {
            File file = new File(pathname);
            if (file.exists()) {
                pathname = file.getAbsolutePath();
            }
            //Excel工具项
            InputStream inputStream = new FileInputStream(pathname);
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                if (row.getRowNum() == 0) {
                    continue;
                }
                TextAchievements textAchievements = new TextAchievements();
                //设置单元格类型
                row.getCell(0).setCellType(CellType.STRING);
                //序号
                String serialNum = row.getCell(0).getStringCellValue();
                //环境管控单元编码
                String unitCode = row.getCell(1).getStringCellValue();
                //单元名称
                String unitName = row.getCell(2).getStringCellValue();
                //省
                String province = row.getCell(3).getStringCellValue();
                //师
                String division = row.getCell(4).getStringCellValue();
                //团
                String regiment = row.getCell(5).getStringCellValue();
                //管控单元分类
                String unitClassify = row.getCell(6).getStringCellValue();
                //空间布局约束
                String spaceRestrain = row.getCell(7).getStringCellValue();
                //污染物排放管控
                String pollutantRestrain = row.getCell(8).getStringCellValue();
                //环境风险防控
                String environmentRestrain = row.getCell(9).getStringCellValue();
                //资源利用效率
                String resourceUtilization = row.getCell(10).getStringCellValue();

                textAchievements.setUnitCode(unitCode);
                textAchievements.setUnitName(unitName);
                textAchievements.setProvince(province);
                textAchievements.setDivision(division);
                textAchievements.setRegiment(regiment);
                textAchievements.setUnitClassify(unitClassify);
                textAchievements.setSpaceRestrain(spaceRestrain);
                textAchievements.setPollutantRestrain(pollutantRestrain);
                textAchievements.setEnvironmentRestrain(environmentRestrain);
                textAchievements.setResourceUtilization(resourceUtilization);
                textAchievementsList.add(textAchievements);
            }
        } else {
            return null;
        }
        String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
        if (!StringUtils.isEmpty(suffix)) {
            if (suffix.equals("shp")) {
                //当为shp文件时，对其进行解析
                fileServerPath = pathname;
            }
            achievementsFile.setFileType(suffix);
        }
        achievementsFile.setFilePath(filePathFinal);
        achievementsFile.setFileName(fileOriginalFileName);
        achievementsFile.setAchievementsTypeId(achievementsType.getId());
        achievementsFile.setIsHistory(0);
        achievementsFiles.add(achievementsFile);
        achievementsFile.setContent(achievements.getContent());
        achievements.setFiles(achievementsFiles);
        for (AchievementsFile file : achievementsFiles) {
            file.setAchievements(achievements);
        }
        return textAchievementsList;
    }

    /**
     * 解析管控单元文本文件
     *
     * @param filePath
     */
    private List<TextAchievements> analysisTextFile1(String filePath) throws IOException {
        List<TextAchievements> textAchievementsList = new ArrayList<>();
        //Excel工具项
        InputStream inputStream = new FileInputStream(filePath);
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        for (Row row : sheet) {
            if (row.getRowNum() == 0) {
                continue;
            }
            TextAchievements textAchievements = new TextAchievements();
            //设置单元格类型
            row.getCell(0).setCellType(CellType.STRING);
            //序号
            String serialNum = row.getCell(0).getStringCellValue();
            //环境管控单元编码
            String unitCode = row.getCell(1).getStringCellValue();
            //单元名称
            String unitName = row.getCell(2).getStringCellValue();
            //省
            String province = row.getCell(3).getStringCellValue();
            //师
            String division = row.getCell(4).getStringCellValue();
            //团
            String regiment = row.getCell(5).getStringCellValue();
            //管控单元分类
            String unitClassify = row.getCell(6).getStringCellValue();
            //空间布局约束
            String spaceRestrain = row.getCell(7).getStringCellValue();
            //污染物排放管控
            String pollutantRestrain = row.getCell(8).getStringCellValue();
            //环境风险防控
            String environmentRestrain = row.getCell(9).getStringCellValue();
            //资源利用效率
            String resourceUtilization = row.getCell(10).getStringCellValue();

            textAchievements.setUnitCode(unitCode);
            textAchievements.setUnitName(unitName);
            textAchievements.setProvince(province);
            textAchievements.setDivision(division);
            textAchievements.setRegiment(regiment);
            textAchievements.setUnitClassify(unitClassify);
            textAchievements.setSpaceRestrain(spaceRestrain);
            textAchievements.setPollutantRestrain(pollutantRestrain);
            textAchievements.setEnvironmentRestrain(environmentRestrain);
            textAchievements.setResourceUtilization(resourceUtilization);
            textAchievementsList.add(textAchievements);
        }
        return textAchievementsList;
    }


    /**
     * 解析环境要素文本文件
     *
     * @param filePath
     */
    private List<LayerFeatures> analysisLayerFeatureTextFile(String filePath) throws IOException {
        List<LayerFeatures> layerFeaturesList = new ArrayList<>();
        //Excel工具项
        //Excel工具项
        InputStream inputStream = new FileInputStream(filePath);
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        for (Row row : sheet) {
            if (row.getRowNum() == 0) {
                continue;
            }
            LayerFeatures layerFeatures = new LayerFeatures();
//            //对应文件英文名
//            String name = row.getCell(0).getStringCellValue();
            //管控单元分类
            String unitClassify = row.getCell(0).getStringCellValue();
            //环境要素
            String environmentFeatures = row.getCell(1).getStringCellValue();
            //要素细类
            String detailFeatures = row.getCell(2).getStringCellValue();
            //空间布局约束
            String spaceRestrain = row.getCell(3).getStringCellValue();
            //污染物排放管控
            String pollutantRestrain = row.getCell(4).getStringCellValue();
            //环境风险防控
            String environmentRestrain = row.getCell(5).getStringCellValue();
            //资源利用效率
            String resourceUtilization = row.getCell(6).getStringCellValue();
            String remark = row.getCell(7).getStringCellValue();

//            layerFeatures.setName(name);
            layerFeatures.setUnitClassify(unitClassify);
            layerFeatures.setEnvironmentFeatures(environmentFeatures);
            layerFeatures.setDetailFeatures(detailFeatures);
            layerFeatures.setSpaceRestrain(spaceRestrain);
            layerFeatures.setPollutantRestrain(pollutantRestrain);
            layerFeatures.setEnvironmentRestrain(environmentRestrain);
            layerFeatures.setResourceUtilization(resourceUtilization);
            layerFeatures.setRemarks(remark);
            layerFeaturesList.add(layerFeatures);
        }
        return layerFeaturesList;
    }

    public static Datasource datasource;
    private long index = 0;

    /**
     * 初始化
     *
     * @param serverPath
     * @param shpDictionary
     * @return
     */
    private void init(String serverPath, String shpDictionary) {
        try {
            Workspace workspace = new Workspace();
            DataImport dataImport = new DataImport();
            ImportSettings importSettings = dataImport.getImportSettings();
            ImportSettingSHP gdbVector = new ImportSettingSHP();
            Datasources datasources = workspace.getDatasources();
            DatasourceConnectionInfo info = new DatasourceConnectionInfo();
            info.setAlias("FFF");
            info.setEngineType(EngineType.UDBX);
            info.setServer(serverPath);//
            Datasource datsource = datasources.open(info);
            datsource.getDatasets().deleteAll();
            gdbVector.setSourceFilePath(shpDictionary);
            gdbVector.setTargetDatasource(datsource);
            importSettings.add(gdbVector);
            ImportResult result = dataImport.run();
            result.getFailedSettings();
            datasource = datsource;
        } catch (Exception e) {

        }
    }

    /**
     * 初始化
     *
     * @param serverPath
     * @param shpDictionary
     * @return
     */
    public void convert(String serverPath, String shpDictionary,String fileName) {
        try {
            Workspace workspace = new Workspace();
            DataImport dataImport = new DataImport();
            ImportSettings importSettings = dataImport.getImportSettings();
            ImportSettingSHP gdbVector = new ImportSettingSHP();
            Datasources datasources = workspace.getDatasources();
            DatasourceConnectionInfo info = new DatasourceConnectionInfo();
            info.setAlias("FFF");
            info.setEngineType(EngineType.UDBX);
            info.setServer(serverPath);//
            Datasource datsource = datasources.open(info);
            datsource.getDatasets().deleteAll();
            gdbVector.setSourceFilePath(shpDictionary);
            gdbVector.setTargetDatasource(datsource);
            importSettings.add(gdbVector);
            ImportResult result = dataImport.run();
            result.getFailedSettings();
            datasource = datsource;

            DatasetVector dataset_red = (DatasetVector) datsource.getDatasets().get(fileName);
            PrjCoordSys m_targetPrjCoordSys = new PrjCoordSys();
            m_targetPrjCoordSys.fromEPSGCode(4490);
            CoordSysTransParameter m_coordSysTransParameter = new CoordSysTransParameter();
            CoordSysTranslator.convert(dataset_red,m_targetPrjCoordSys, m_coordSysTransParameter, CoordSysTransMethod.MTH_GEOCENTRIC_TRANSLATION);
            System.out.println("success");
        } catch (Exception e) {

        }
    }

    /**
     * 拓扑检查-面和面重叠检查
     *
     * @param firstShpName
     * @param secondShpName
     * @return
     */
    private boolean topologyAnalysis(String firstShpName, String secondShpName) {
        try {
            index++;
            String outputStr = "output" + String.valueOf(index);
            String outputStrSelf = "outputSelf" + String.valueOf(index);
            DatasetVector dataset_red = (DatasetVector) datasource.getDatasets().get(firstShpName);
            DatasetVector dataset_red1 = (DatasetVector) datasource.getDatasets().get(secondShpName);
//        Recordset recordset = dataset_red.getRecordset(false, CursorType.DYNAMIC);
            //面无重叠
            DatasetVector m_resultDatasetVector_1 = TopologyValidator.validate(dataset_red, null, TopologyRule.REGION_NO_OVERLAP, 0.00000001, null, datasource, outputStr);
            //面和面重叠检查
            DatasetVector m_resultDatasetVector = TopologyValidator.validate(dataset_red, dataset_red1, TopologyRule.REGION_NO_OVERLAP_WITH, 0.00000001, null, datasource, outputStrSelf);
            System.out.println(m_resultDatasetVector.getRecordCount());
            if (m_resultDatasetVector.getRecordCount() > 0) {
                return true;
            }
        } catch (Exception e) {
            return true;
        }
        return false;
    }

    /**
     * 拓扑检查-面和面重叠检查
     *
     * @param firstShpName
     * @param secondShpName
     * @return
     */
    private String topologyAnalysis1(String firstShpName, String secondShpName) {
        String result = "";
        try {
            index++;
            String outputStr = "output" + String.valueOf(index);
            String outputStrSelf = "outputSelf" + String.valueOf(index);
            DatasetVector dataset_red = (DatasetVector) datasource.getDatasets().get(firstShpName);
            DatasetVector dataset_red1 = (DatasetVector) datasource.getDatasets().get(secondShpName);
//        Recordset recordset = dataset_red.getRecordset(false, CursorType.DYNAMIC);
            //面无重叠
            DatasetVector m_resultDatasetVector_1 = TopologyValidator.validate(dataset_red, null, TopologyRule.REGION_NO_OVERLAP, 0.0000001, null, datasource, outputStr);
            //面和面重叠检查
            DatasetVector m_resultDatasetVector = TopologyValidator.validate(dataset_red, dataset_red1, TopologyRule.REGION_NO_OVERLAP_WITH, 0.0000001, null, datasource, outputStrSelf);
            System.out.println(m_resultDatasetVector.getRecordCount());
            Recordset recordset = m_resultDatasetVector.getRecordset(false, CursorType.STATIC);
            int count = recordset.getRecordCount();
            if (count == 0) {
                return null;
            } else {
                recordset.moveFirst();
                for (int i = 0; i < recordset.getRecordCount(); i++) {
                    Object valueID1 = recordset.getFieldValue("ErrorObjectID_1");
                    Object valueID2 = recordset.getFieldValue("ErrorObjectID_2");
                    if (valueID1 != null && valueID2 != null) {
                        int[] id1 = new int[]{(int) valueID1};
                        int[] id2 = new int[]{(int) valueID2};
                        Recordset recordset1 = dataset_red.query(id1, CursorType.STATIC);
                        Recordset recordset2 = dataset_red1.query(id2, CursorType.STATIC);
                        if (recordset1 != null && recordset2 != null) {
                            recordset1.moveFirst();
                            recordset2.moveFirst();
                            String bm1 = recordset1.getFieldValue(Constants.HJYSGKFQBM).toString();
                            String bm2 = recordset2.getFieldValue(Constants.HJYSGKFQBM).toString();
                            result += bm1 + ":" + bm2 + ";";
                        }
                    }
                    recordset.moveNext();
                }
            }
        } catch (Exception e) {
            return null;
        }
        return result;
    }

}
